Треугольник

CSS Triangle

The idea is a box with zero width and height. The actual width and height of the arrow is determined by the width of the border. In an up arrow, for example, the bottom border is colored while the left and right are transparent, which forms the triangle.

.arrow-up < width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 5px solid black; >.arrow-down < width: 0; height: 0; border-left: 20px solid transparent; border-right: 20px solid transparent; border-top: 20px solid #f00; >.arrow-right < width: 0; height: 0; border-top: 60px solid transparent; border-bottom: 60px solid transparent; border-left: 60px solid green; >.arrow-left

For an equilateral triangle it’s worth pointing out that the height is 86.6% of the width so (border-left-width + border-right-width) * 0.866% = border-bottom-width

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

Hi. How can i change the color inside the triangle ? And say, if i just need to make sure that the bottom part of the triangle is not there, how do i do that as well ?

Hey thank you very much!
It worked!
But can you tell me how to give a border to this type of triangle?(As it is only made up of the border of a div!!)

Hey Tarun!
As it is only made up of border, all you can do is increase the size of that border, if you really wish to, because that’s all you can do to it. And you’ll have to give negative margin of equal pixels as those of the border size to maintain alignment.

@mixin equilateral-triangle($direction, $size, $color) < width: 0; height: 0; @if $direction == 'up' < border-left: em($size) solid transparent; border-right: em($size) solid transparent; border-bottom: em($size) solid $color; >@else if $direction == 'down' < border-left: em($size) solid transparent; border-right: em($size) solid transparent; border-top: em($size) solid $color; >@else if $direction == 'right' < border-top: em($size) solid transparent; border-bottom: em($size) solid transparent; border-left: em($size) solid $color; >@else if $direction == 'left' < border-top: em($size) solid transparent; border-bottom: em($size) solid transparent; border-right: em($size) solid $color; >> 

I wrote a little addition to this article to achieve the same but with some functional SCSS to the DRY rescue. http://powdertothepeople.tv/2015/06/29/Functional-SCSS/

Thank you for the clear explanation! There are several pages which show how to put arrows on tooltips, etc but they left me completely mystified as to how they worked. Now at last, thanks to this page, I understand!

It’s basicly like a giant 3D border-corner. (when the left and top border-color are different the edge is diagonal, that’s being used to make this triangle).

Thanks, TeMc, now it all makes sense. By the way, it’s fun to play with the inner div’s right border width, and change the shape and size of the triangle!

thanks for making it clear.. thanks even to admin to share a lovely tricks 🙂 am very greatful to this website.. 🙂

Thanks for the reminder! It hass been so long since I’ve noticed how different border colors act together (think table cells).

-moz-transform: rotate(1deg); -o-transform: rotate(1deg); -webkit-transform: rotate(1deg); transform: rotate(1deg); 

Wow, nice job with the flag on your link… Also, I wanted to ask why do you use ‘dashed’ instead of ‘solid’? I wasn’t able to understand the difference.. Cheers & congrats again.

 .left-arrow < border-color: transparent black; border-style: solid; border-width: 20px 20px 20px 0px; height: 0px; width: 0px; >.right-arrow < border-color: transparent black; border-style: solid; border-width: 20px 0px 20px 20px; height: 0px; width: 0px; >.down-arrow < border-color: black transparent; border-style: solid; border-width: 20px 20px 0px 20px; height: 0px; width: 0px; >.up-arrow 

Thanks, Otto. I wasn’t sure what the syntax was for 2 values on the border-color until I found this article, which may help others; https://developer.mozilla.org/en-US/docs/Web/CSS/border-color

Читайте также:  Changing hover color in html

If the dimensions of the triangle aren’t symmetrical, you tend to get those jagged lines. It appears to be more noticeable in Webkit, for some reason–not sure why.

You may have figured this out, but here goes anyway: For webkit, to get the lines smooth, add the following rule: transform: rotate(360deg); Play with different deg depending on your arrow’s direction.

try adding “box-shadow: 0 0 2px orange;” to the triangle. it might help. if not reducing the “2px” in it or incressing will change the blur strangth of the shadow.

Cool trick, I tried it first after seeing it elsewhere.
Then I came across the ivy-leaf trick on this website, and if you want the triangle to scale with the text, change the ivy leaf to a triangle. down: \25bc
up: \25b2
right: \25b6 I couldn’t find a “map”, but if you play around changing the last 4 digits in the url, you can find all kinds of cool stuff.
http://www.decodeunicode.org/en/u+25bc

You can use those triangles to create Real-time 3D objects in IE6. Yes, IE6!
http://www.uselesspickles.com/triangles/ Borders can also build a house:
http://www.designdetector.com/tips/3DBorderDemo2.html

I noticed a small issue with this technique in Firefox 5.0 (Win). FF 5.0 renders a light stroke on the front sides of the triangle. Here’s a link to a jsFiddle that replicates the issue: http://jsfiddle.net/brightlight/4DmFk/ Obviously, you’ll need to view that in FF 5.0 (Win) to see what I’m talking about.

Update: Changing the border style to “inset” on the transparent sides of the element seems to fix this issue in Firefox 5 and 6. Other browsers continue to render the triangles fine even after this border-style adjustment.

great tutorial.
@ted: great tip on the “inset”. Was working my mind through the reason for the strange micro-border!

In scenarios like below I get pixelation in Safari, IE and some yet less in FF. Is anyone else getting this ?
.point_bottom border-left: 200px solid transparent;
border-right: 200px solid transparent;
border-top: 80px solid #FF0000;
bottom: 0;
height: 0;
left: -101px;
position: absolute;
width: 0;
>

If the triangle is not symmetrical, it won’t look smooth. Basically, it’s like trying to draw a straight line at a 30-degree angle in a bitmap image. The line will always look a little jagged. This trick is just an exploitation of CSS behavior–I don’t believe CSS was intended to do this sort of thing. If you want truly straight lines at whatever angle, you might want to explore SVG.

You do some limited drop shadows using a pseudo-element. Just position it a little different than the original triangle shape and then change the color and/or transparency. A little rotation looks nice with this effect, too. I saw it in a NetTuts piece recently.

Is it possible to use this on a [submit] button?
so the end result would look like this https://skitch.com/iestynx/fa6et/artwork I’m a bit new to this so sorry if it’s a stupid question. Thanks

Lestyn, I guess the button can’t be achieved using a div.I tried creating the same using two div and i got the same. Here’s my Try http://jsfiddle.net/smkarthick/vb5Tv/3/

The problem that some people have been reporting with inaccurate edges is to do with antialiasing and the fact that transparent is equivalent to rgba(0, 0, 0, 0) —transparent black. When combined with antialiasing, this produces a result which is not what the author intended. I am not aware whether any browsers used antialiasing back in mid-2009, but now, Firefox distinctly does. I am in the process of writing a blog post (as part of starting a blog, which makes it take longer…) dealing with this particular subject with full details, explanations, the caveats, et cetera, and I initially planned on waiting till I had that done before posting this. But as it’s been several weeks since I began to plan it and will probably be at least as many more until it’s ready and posted, I figured I should try to stop people using transparent when they don’t mean it before it’s too too late. My general recommendation is to avoid using transparent unless you know that it’s suitable (i.e. black is the touching colour). If you have to care about browsers that don’t support rgba() values (IE8 and earlier), then specify it as transparent and add a border-left/right/top/bottom-color value after it with the correct rgba value to override it and make it correct.

Читайте также:  Android java sdk reference

I was just playing around with the antialiasing issue and found that if I set the border widths to make the triangle symmetrical and then do a scale transform to the triangle to stretch it to the right dimensions, it forces the browser to antialias the edges and gets rid of the jaggedness.

The transform trick works a treat in webkit! Unfortunately for me it introduces issues in Firefox. There’s now a vertical split down the middle of the triangle whenever I scale it up or down… http://jsfiddle.net/bensmithett/fEjJ3/

I’ve noticed a problem in IE9 if you use this to style a button as an arrow. If you define a style for all 4 borders, it will show them all (even if they’re transparent). Since you’ll want to reset all of the borders to avoid the default button style, this causes a problem. It also does some funny stuff with the sizes, so even if you only define the 3 sides you need, it doesn’t look right. So far, the best I’ve found for a workaround is to use a (or a div) instead, even though it’s less semantic.

Источник

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

Примеры как сделать различные вариации треугольников с помощью CSS-свойства border.

Закрашенные треугольники

/* Направленный вправо */ span
/* Верхний правый угол */ span

Треугольники с рамкой

/* Направленный вверх */ span < display: inline-block; border: 30px solid transparent; border-bottom: 30px solid orange; position: relative; >span:after
/* Направленный вниз */ span < display: inline-block; border: 30px solid transparent; border-top: 30px solid orange; position: relative; >span:after
/* Направленный влево */ span < display: inline-block; border: 30px solid transparent; border-right: 30px solid orange; position: relative; >span:after
/* Направленный вправо */ span < display: inline-block; border: 30px solid transparent; border-left: 30px solid orange; position: relative; >span:after
/* Левый верхний угол */ span < display: inline-block; border-top: 40px solid orange; border-right: 40px solid transparent; position: relative; >span:after
/* Верхний правый угол */ span < display: inline-block; border-top: 40px solid orange; border-left: 40px solid transparent; position: relative; >span:after
/* Нижний правый угол */ span < display: inline-block; border-bottom: 40px solid orange; border-left: 40px solid transparent; position: relative; >span:after
/* Нижний левый угол */ span < display: inline-block; border-bottom: 40px solid orange; border-right: 40px solid transparent; position: relative; >span:after

Комментарии

Другие публикации

Диалоговые окна JS

Генерация счета на оплату PDF PHP

С помощью расширения dompdf можно легко сформировать PDF файл. По сути, dompdf — это конвертер HTML в PDF который.

Читайте также:  What was python named after

Фиксированное горизонтальное меню с активными пунктами

Подменю в dropdown Bootstrap

Разработчики Bootstrap начиная с третьей версии удалили поддержку подменю из-за того, что им никто не пользуется и на мобильных эта функция не актуальна. Ниже представлены примеры как сделать.

Блокировка многократной отправки формы

Из-за отправки файла, медленного интернета или тормозящего браузера, пользователь может нажать кнопку отправки формы.

jQuery UI Slider

jQuery UI Slider – гибкий плагин, который позволяет создать элементы интерфейса в виде ползунков в различных вариантах.

Источник

Треугольники через CSS

На сайтах треугольники применяются сплошь и рядом как часть дизайна элементов, например, они служат указателем на какой-то объект, направляя внимание читателя в нужное место. Также треугольники выполняют декоративные функции, делая блоки, где они применяются, более изящными и современными. На рис. 1 показан пример использования треугольника в дизайне.

Треугольники в веб-дизайне

Рис. 1. Треугольники в веб-дизайне

Напрямую сделать треугольник средствами CSS нельзя, поэтому доступны два метода, позволяющих его добавить — через border и transform .

Использование border

Хотя границы, создаваемые через свойство border , напрямую не имеют отношения к треугольникам, именно border используется для этого наиболее часто. Если задать нулевую ширину и высоту элемента, а также установить достаточно толстую границу, то мы увидим набор из четырёх треугольников (рис. 2). Для наглядности границы на всех сторонах установлены разного цвета.

Рис. 2. Добавление border к элементу

Оставляя только нужную границу, а остальные делая прозрачными, мы получим треугольник нужного цвета (рис. 3).

Рис. 3. Элемент с прозрачными границами

В примере 1 показано добавление треугольника к блоку через псевдоэлемент ::after .

Пример 1. Блок с треугольником

        

Для абсолютно позиционированных элементов нулевую ширину и высоту указывать не обязательно.

За счёт комбинирования границ можно получить ещё четыре вида треугольников, что в сочетании с уже упомянутыми даёт нам восемь вариантов. Их вид и требуемый код приведён в табл. 1.

Источник

Геометрические фигуры на CSS

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

Квадрат

Прямоугольник

Круг

Овал

Треугольник вверх

Треугольник вниз

Треугольник налево

Треугольник направо

Треугольник в левом верхнем углу

Треугольник в правом верхнем углу

Треугольник в левом нижнем углу

Треугольник в правом нижнем углу

Параллелограмм

Трапеция

Звезда (6-конечная)

Звезда (5-конечная)

 #star-five < margin: 50px 0; position: relative; display: block; color: red; width: 0px; height: 0px; border-right: 100px solid transparent; border-bottom: 70px solid red; border-left: 100px solid transparent; -moz-transform: rotate(35deg); -webkit-transform: rotate(35deg); -ms-transform: rotate(35deg); -o-transform: rotate(35deg); >#star-five:before < border-bottom: 80px solid red; border-left: 30px solid transparent; border-right: 30px solid transparent; position: absolute; height: 0; width: 0; top: -45px; left: -65px; display: block; content: ''; -webkit-transform: rotate(-35deg); -moz-transform: rotate(-35deg); -ms-transform: rotate(-35deg); -o-transform: rotate(-35deg); >#star-five:after

Пятиугольник

Шестиугольник

#hexagon < width: 100px; height: 55px; background: red; position: relative; >#hexagon:before < content: ""; position: absolute; top: -25px; left: 0; width: 0; height: 0; border-left: 50px solid transparent; border-right: 50px solid transparent; border-bottom: 25px solid red; >#hexagon:after

Восьмиугольник

#octagon < width: 100px; height: 100px; background: red; position: relative; >#octagon:before < content: ""; position: absolute; top: 0; left: 0; border-bottom: 29px solid red; border-left: 29px solid #eee; border-right: 29px solid #eee; width: 42px; height: 0; >#octagon:after

Сердечко

#heart < position: relative; width: 100px; height: 90px; >#heart:before, #heart:after < position: absolute; content: ""; left: 50px; top: 0; width: 50px; height: 80px; background: red; -moz-border-radius: 50px 50px 0 0; border-radius: 50px 50px 0 0; -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); -ms-transform: rotate(-45deg); -o-transform: rotate(-45deg); transform: rotate(-45deg); -webkit-transform-origin: 0 100%; -moz-transform-origin: 0 100%; -ms-transform-origin: 0 100%; -o-transform-origin: 0 100%; transform-origin: 0 100%; >#heart:after

Знак бесконечности

#infinity < position: relative; width: 212px; height: 100px; >#infinity:before, #infinity:after < content: ""; position: absolute; top: 0; left: 0; width: 60px; height: 60px; border: 20px solid red; -moz-border-radius: 50px 50px 0 50px; border-radius: 50px 50px 0 50px; -webkit-transform: rotate(-45deg); -moz-transform: rotate(-45deg); -ms-transform: rotate(-45deg); -o-transform: rotate(-45deg); transform: rotate(-45deg); >#infinity:after

Источник

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