Shadow for css triangle

CSS box shadow around triangle

The following tutorial shows you how to use CSS to do «CSS box shadow around triangle».

CSS Style

The CSS style to do «CSS box shadow around triangle» is

.triangle-with-shadow !-- w w w . d e m o2 s . c o m --> width:100px; height:50px; position:relative; overflow:hidden; box-shadow:0 16px 10px -15px rgba(0,0,0,0.5); > .triangle-with-shadow:after < content:""; position:absolute; width:50px; height:50px; background:#999; transform:rotate(45deg); -ms-transform:rotate(45deg); -moz-transform:rotate(45deg); -webkit-transform:rotate(45deg); -o-transform:rotate(45deg); top:25px; left:25px; box-shadow:-1px -1px 10px 0px rgba(0,0,0,0.5); >

HTML Body

body> div >"triangle-with-shadow">   

The following iframe shows the result. You can view the full source code and open it in another tab.

html> head> meta name="viewport" content="width=device-width, initial-scale=1"> style id="compiled-css" type="text/css"> .triangle-with-shadow !-- ww w . d e m o 2 s . c om --> width: 100px; height: 50px; position: relative; overflow: hidden; box-shadow: 0 16px 10px -15px rgba(0,0,0,0.5); > .triangle-with-shadow:after < content: ""; position: absolute; width: 50px; height: 50px; background: #999; transform: rotate(45deg); -ms-transform:rotate(45deg); /* IE 9 */ -moz-transform:rotate(45deg); /* Firefox */ -webkit-transform:rotate(45deg); /* Safari and Chrome */ -o-transform:rotate(45deg); /* Opera */ top: 25px; left: 25px; box-shadow: -1px -1px 10px 0px rgba(0,0,0,0.5); >  body> div >"triangle-with-shadow">    

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Треугольники с тенью на CSS

Скорее всего, вы уже знаете, как сделать треугольник на чистом CSS, использовав свойство border. Если же не знаете, то можно почитать, например, здесь. Но что, если вам понадобятся треугольники с тенью?

Классическая манипуляция с бордером не может изменить форму объекта, это всего лишь визуальный обман.
Т.е. нельзя просто взять и добавить box-shadow к такому треугольнику, потому что получим что-нибудь в таком роде:

Давайте посмотрим на несколько альтернативных решений.

Используем Unicode

Среди unicode-символов есть несколько треугольников. Например:

Больше вариантов можно найди здесь.
Если использовать такой вариант треугольника, то с ним можно делать всякие забавные штуки

Т.е. цвет, тень, размер, все на ваш выбор. Кроме того, если форма треугольника вас не устраивает, можно воспользоваться CSS3 трансформациями для того, чтобы растянуть или повернуть его.

Мне нравится эта техника, но в ней есть несколько проблем, и главная из них — слабая поддержка CSS3-трансформаций браузерами. Особенно в IE8. Хотя с другой стороны, эта статья о тенях, поэтому нам нужен CSS3 в любом случае. К тому же, старые браузеры могут иметь проблемы с unicode-иконками сами по себе.

Метод Double-Box

Зная CSS3 на неплохом уровне, можно использовать еще один метод, где используется контейнер с overflow:hidden с другим контейнером внутри, который повернут внутри внешнего на 45 градусов. Таким образом, видимая часть и будет нашим треугольником. Теперь можно использовать box-shadow для обоих контейнеров чтобы добавить к ним тень и достичь нужного эффекта.

.triangle-with-shadow < width: 100px; height: 100px; position: relative; overflow: hidden; box-shadow: 0 16px 10px -17px rgba(0,0,0,0.5); >.triangle-with-shadow:after < content: ""; position: absolute; width: 50px; height: 50px; background: #999; transform: rotate(45deg); /* Не забываем про префиксы */ top: 75px; left: 25px; box-shadow: -1px -1px 10px -2px rgba(0,0,0,0.5); >

Обратите внимание, что используется негативное значение радиуса для родительского блока, таким образом образовывается тень только с одной стороны.
Ссылка на пример

Читайте также:  Php current time in milliseconds

Просто используем изображение

Я не большой фанат такого способа, потому что это или дополнительный HTTP запрос, или дополнительные манипуляции со спрайтом. К тому же, простое изображение не очень подходит для адаптивного дизайна — проблемы с масштабированием, плюс будет видна пикселизация на дисплеях с повышенной плотностью пикселей. В то же время, первые две техники позволяют манипулировать треугольниками как векторными объектами — без всяких пикселизаций.

Internet Explorer продолжает вставлять палки в колеса, накладывая некоторые ограничения на использование первых двух техник, однако нам никто не мешает вовсю применять их в верстке мобильных сайтов.

Дополнительный вариант: используем canvas

Здесь придется выйти за рамки CSS, однако эта техника также довольно перспективна

var canvas = document.getElementById('triangle'); var context = canvas.getContext('2d'); context.beginPath(); context.moveTo(10, 25); context.lineTo(40, 10); context.lineTo(40, 40); context.lineTo(10, 25); context.closePath(); context.shadowColor = "rgba(0, 0, 0, 0.4)"; context.shadowBlur = 7; context.shadowOffsetX = 2; context.shadowOffsetY = 5; context.fillStyle = "rgba(132, 28, 255, 0.8)"; context.fill(); 

Источник

Drawing Triangles with CSS

At some point, most of the front-end developers have had to search about drawing triangles. It can be a bit challenging, as CSS by default represents everything as a rectangle. On the brighter side, it also offers more than one way to generate triangles. This article will go through a series of examples.

Selective Borders

CSS borders are triangle shaped, by default. If we have an element with zero physical dimensions and a thick border on all four sides with unique colors, we will observe that the borders are just 4 triangles clamped together. Let’s see it in action.

We create an empty element and give it four, thick borders with unique colors.

As observed, the output is nothing more than 4 triangles sharing a common point, but we just want the bottom border here.

Let’s start by setting the top border-width to 0:

border-width: 0 150px 150px 150px; 

To get rid of the yellow and green borders, we can use a transparent color for them.

border-color: transparent transparent #48abe0 transparent; 

To make triangles that point diagonally, we can just set another border width to 0. Let’s set the top and left borders to 0:

border-width: 0 150px 150px 0; 

Now we can make triangles pointing in 8 different directions:

border-color: transparent transparent #48abe0 transparent; border-width: 0 150px 150px 150px; 
border-color: #48abe0 transparent transparent transparent; border-width: 150px 150px 0 150px; 
border-color: transparent #48abe0 transparent transparent; border-width: 150px 150px 150px 0; 
border-color: transparent #48abe0 transparent transparent; border-width: 150px 0 150px 150px; 
border-color: #48abe0 transparent transparent transparent; border-width: 150px 0 0 150px; 

If you want to use this method to create triangles pointing in arbitrary directions, then it can require some more complicated maths to get the transformations right. You can use our triangle generator to generate it for you instead. Then you can generate all sorts of triangles such as this:

Читайте также:  Отличие атрибута от свойства html

Path Clipping

CSS offers a powerful property named clip-path. This property enables you to take an HTML element and draw a region over it. The content inside the region will be visible while the rest will be hidden. This property offers a range of default regions that span shapes, custom path elements, custom SVGs, and attributes of CSS Box-Model. We can use the polygon function to draw a triangle over our element by providing 3 coordinates that combine to make a triangle.

Let’s create an element and set a background image on it.

Next, we only need to clip a triangle out of it. We will draw a polygon on it with 3 points. The Polygon function, in our case, will take 3 coordinates as percentages from the origin. The origin is the top left corner of the element. So x values will travel from that point towards the right direction while the y values will travel downwards. For example, a red dot drawn at (30%, 70%) will land at the place shown in the following image:

Let’s choose 3 points that will form the triangle of our requirement. We take the values (50% 0%), (0% 100) and (10%, 100%). The markers at these points will look as follows:

Let’s clip our element to the content (triangle) inside these points.

You can also use our clip-path generator to generate the required property value for you.

Creating a Triangle having a Background Gradient

We can reuse path clipping to clip out a triangle from a gradient.

Creating a Bordered Triangle

Let’s suppose we have a requirement to build a triangle that has a border of a different color. Following is the expected output.

We can build such a bordered triangle as a combination of 2 triangles, one on top of the other. We will use a single HTML element though. The border triangle will go as its main styling, while the inner triangle will be the styling of its ::after pseudo-element child. We will use the same technique of drawing 3 transparent and 1 colored border. The child triangle will have a border width less than the parent’s width. The difference in border width will be the exact value of the required border thickness. And we will use absolute positioning with top and left offsets to adjust the positioning of the child triangle over the parent triangle.

.triangle-border < position: relative; width: 0; border-color: transparent transparent black transparent; border-width: 101px 101px 101px 101px; border-style: solid; margin: auto; margin-top: -70px; >.triangle-border-inner:after

And we are done. We have the bordered triangle.

Читайте также:  Dle smtp class php

Box Shadow for Path Clipped Triangles

If you are drawing your triangle using path clipping and want to have a box-shadow for the triangle, you will encounter the problem of the box-shadow not being rendered around the triangle. This is because clip-path clips out shadow as well. You could apply the box-shadow to a wrapper around your triangle. But since, by default, everything is a box in CSS, the shadow will be rectangular. You can fix this by using the drop-shadow filter on the wrapper, which shrinks the shadow of the parent and wraps it perfectly to the child.

.triangle-wrapper < filter: drop-shadow(5px 5px 5px rgba(0, 0, 0, 0.3)); >.triangle-linear-gradient-bg

There we go. We have a path-clipped triangle with an accurately wrapping shadow.

Drawing A Triangle Using 2 Gradients

We can also create a triangle by applying 2 diagonal gradients to an element. Each diagonal will form half of the triangle. Thus, we want our gradients to be half transparent and cover only 50% width of the element.

The following example uses 2 gradients with different colors to demonstrate how the triangle is formed. The blue gradient is a half-width gradient in the bottom-right direction placed in the left half of the element while the purple gradient is directed bottom-left and placed in the right half of the element. The results may not be super precise across different rendering engines, and you may see a gap line of one pixel or a half where the 2 gradients meet. It also has the problem that if the aspect ratio of the element changes at all, then the triangle won’t resize itself to fit.

Note: Transparent borders and path-clipping are relatively easier ways of drawing a triangle. They are also not prone to leaving half-pixel gaps down the middle.

.triangle-double-bg-gradients

You can experiment with this in our Gradient Generator.

Conclusion

Drawing triangles in CSS can be a bit challenging. But the good news is that CSS offers a lot of ways to draw them. This article has compiled a series of different methods.

UnusedCSS helps website owners remove their unused CSS every day. See how much you could save on your website:

You Might Also Be Interested In

Источник

Оцените статью