Треугольник

Как сделать треугольник на CSS

Свойство border-width нельзя устанавливать в процентах.

Генератор треугольника с border

  

border-radius : с закруглёнными углами

clip-path : обрезать HTML-элемент

Можно делать адаптивные треугольники любой формы с любой фоновой картинкой, но пока поддержка браузеров хромает.

Генератор треугольника с clip-path

  

shape-inside : текст в треугольнике

С shape-outside , внешний текст будет обтекать элемент. Лучше использовать свойство shape-inside , но оно не имеет поддержки в браузерах.

  
текст

linear-gradient в background : фон наполовину

Генератор треугольника с background

  

linear-gradient в mask : наложить маску на HTML-элемент

Обрезает всё, выходящее за рамки треугольника. Можно делать адаптивные треугольники с любым фоном и любой формы, если вместо linear-gradient использовать SVG, но пока поддержка браузеров хромает.

Генератор треугольника с mask

  

Символ треугольника

Резиновый треугольник SVG

Одна из самых простых фигур, которой достаточно поля 2 на 2.

Генератор треугольника с SVG

width="7em" height="7em" viewBox vydelit">0 0 2 2" preserveAspectRatio="none"> width и/или height можно задать в процентах --> 0,0 2,0 1,2"/> 

Kliwi Ru Просто потрясающе сколько труда вы в один пост вкладываете. NMitra Ох, да. Стараюсь сделать так, чтобы потом самой было в удовольствие пользоваться.

Источник

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

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

Читайте также:  Css how to make margins

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

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

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

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

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

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

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

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

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

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

        

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

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

Источник

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

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.

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.

Источник

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