Hacker News new | past | comments | ask | show | jobs | submit login
Animation to Explain CSS Triangles (codepen.io)
227 points by grinnick on Oct 7, 2013 | hide | past | favorite | 104 comments



Man, this is a powerful teaching technique - I knew all this, but I don't think I really really understood it until just now. I hope more people start writing animated explanations for web stuff. Maybe someone could do one for CSS menu systems or side bar, sticky footer, type stuff. Or even the Bootstrap grid system.


I'm sorry, I have very little experience with web design, but is this the supposed way to create a triangle? It seems weird there would be no way to build shapes with primitives.


It's the only way to do it with pure CSS. A more sane approach would be to use a raster or vector image. It is pretty silly.


It is a bit insane, however this allows you to change the color, dimensions, transparency at runtime. A raster doesn't allow you to do this, and, while SVG is scriptable, browser support is spotty.

This hack on the other hand will work in every browser all the way back to Netscape Navigator or earlier.


Better to use Arial unicode characters like &#x25B2 or &#x25BC ASCII encodings and UTF-8 More logical and you can apply all the text styling like color, shadows, skewing, rotate, jquery prepends etc. Put it inside a div and it can go it wherever you want. And it wouldn't be a hack. Some hacks are awesome.. and others are nice playful things but not to be taken with any kind of serious inquiry.


Positioning that accurately would be a massive nightmare due to font rendering differences between OSes and browsers.


I've found that right combination of display: inline-block, position: relative, positioning and margins will get it where you need every time.


What happens when a user agent overrides your preferred font size?


Serious problem. I usually have my page magnification jacked up to reduce eye strain, and it's amazing how many things go wrong on the pages I browse. Don't use a clever hack without testing how it looks after a few cmd-+ (ctrl-+) resizings.


Just don't use font-size and line-heights that references pixels for the <span> containing your arrow and you should be fine. It might not be perfectly aligned, but it won't break.


No, having to open an image editor to create a simple shape you can make in CSS is silly. So is an additional, unnecessary HTTP request.


You can write SVG by hand and embed it in HTML. This requires no use of an external editor nor any extra HTTP request.

  <svg height=10 width=20>
      <polygon fill=red stroke-width=0 
         points="0,10 20,10 10,0" />
  </svg>
If you want to include it in your CSS, you can include it via a data URI, though you need to embed it as an actual XML document (within an HTML document, you can skip the namespace and use HTML syntax which doesn't require quotes around attributes) and can't include line breaks so the syntax is a little bit more cumbersome:

  .triangle {
      background: url("data:image/svg+xml;charset=utf-8,<svg height='10' width='20' xmlns='http://www.w3.org/2000/svg'><polygon fill='red' stroke-width='0' points='0,10 20,10 10,0' /></svg>") no-repeat left center;
      width: 20px;
      height: 10px;
  }
Examples of both in action: http://jsfiddle.net/jtR4G/


No, making a shape in CSS is silly. CSS is for styling not drawing.

If you want to make a triangle, without an additional (unnecessary) HTTP request, you should use the appropriate web tech which is SVG.

Just like all other resources you can easily embed an SVG in your HTML if you're being stingy on the requests (which is a good thing).


not all browsers support SVG (namely IE8). for folks who have to support LOB, this is still an issue.


On the other hand, callout arrows seem like a perfectly good case of something that doesn't necessarily need to be present for the site to function.

If your compatibility goals are pixel-perfect compatibility with IE8, this is an issue (and my thoughts and prayers are with you), but if your site simply needs to be functional, callout triangles wouldn't be on my top 10 things to worry about.


Sure, you can treat this as a hack to support older browsers. But with modern browsers, or once those older browsers fall to low enough market share, just embed SVG.


Back in the real world, however, we can't use the ideal solution every time because of browser support. Thus, the easiest, most flexible option is CSS.


It's not really the most flexible option. It allows you to make only a fairly limited type of triangle, only pointing in one of eight directions.

If you want compatibility with older versions of IE, use both SVG and VML, depending on the browser (VML for IE 8 and earlier, SVG for everything else). This gives you a lot more flexibility (you can draw any polygon, arc, or bezier curve that you want), and compatibility all the way back to IE 5.


I'm racking my brain trying to see the 8 directions. I only see 4: up, down, left & right. Care to explain the other 4?


Got it from here: http://apps.eky.hk/css-triangle-generator/

Here's a series of examples showing how it works (not a fun animation like the OP, but a little easier to follow): http://jsfiddle.net/X8gXS/

Basically, you can get any triangle as long as at least one of the sides is horizontal or vertical.


Ah... I see it now. Thanks.


But you don't need triangles, they're not semantic, just ask W3C.


Touche. The sooner people realize the web is a presentation thing the sooner we can get our sanity back.

sadly, we will see some dozen iterations of 'flash' until that day finally comes. and html5 js shenanigans are only the third...


...and all those impaired people and people with old and slow devices are finally locked out of our new shiny "sane" web.

The web isn't just one visual presentation layer, its a multitude of presentation layers for all kind of people and that demands some compromise.


That seems like a false dichotomy. Why should a nice graphic layer immediately exclude everything else?


It is not, if you frame it like that. But my parent claimed implicitly that the w3c needs to see the web as a pure presentational layer. I have nothing against graphical layers, but a semantic web should stay priority #1 if you ask me.

Also: A lot of the shiny new web apps developed during the last few years are unusable with screen readers and/or on low end devices. As long as we can have graceful degradation, i have nothing against more graphical aspects.


riiight. because the current solution of listening to a webapp via jaws is perfect. They get all the content, which only appears in the end of animations during that nifty scrolling effect.

Everyone that needs accessibility is already screwed with regular web presentation hacks. And having to add more presentation hacks to get the presentation right only screw them more.

Accepting the web is a presentation, the effort a few sites do to add accessibility to the hacks could be spent adding micro formats to the page content or something, benefiting blinds and people just wanting a easier way to get the content.

There are several solutions to problems. And the current state of accessibility on the web is not a prime example of a good one.


Isn't it kinda degrading that while designing CSS no-one came up with the idea that people would like to have a triangle from time to time?


Back then there were images for that; later there was SVG. Triangles with CSS don't actually solve a problem CSS intended to solve.


Back then there were images for borders and even images for padding. CSS solved that. If you add borders why can't you add triangles as well?

SVG would be awesome if it could be freely intermixed with HTML. I think I'd ditch HTML for everything other than text boxes and forms.


I haven't seen border images in the wild since CSS added them, I think (apart from examples). Perhaps that was solving a 1998 use-case in 2008. Nevertheless, CSS is still based on styling runs of text and boxes of content. Boxes usually aren't triangular.

As for HTML in SVG, there is foreignObject [4.72], but browser support is spotty in places. And wrapping text in arbitrary shapes is on the roadmap for SVG 2, if I remember correctly. But we'll be a bit older when that's universally implemented ;-)

[4.72] https://developer.mozilla.org/en-US/docs/Web/SVG/Element/for...


Border images are great for making resizable buttons. I've used them often in places where support is guaranteed (e.g., Chrome extensions).


Where does it stop though? Should CSS provide solutions for polygons too? I think borders are a legitimate styling issue that CSS rightly solves, if only for styling tables. I'm not sure that it's CSS's job to create shapes as well - that, in my mind, is definitely the role of images or SVG.


Not really, I was under the impression CSS was for styling things not for creating them. If we're going to start creating shapes out of CSS then its kinda going out of scope of what it was designed for.


It's just a hack. If you want to create a triangle you'll either draw it on a CANVAS or use SVG. You just cant for instance, put a text in a triangle easily with CSS today(at least in a cross-browser way).


Sure you can - you just write it in another DIV, positioned above your triangle. Or did I misunderstand you?

The beauty for me is not in the hack itself though, it is in the way it is presented - I adore the simplicity of this approach. Kudos!


Well, then the text isn't really "in" the triangle, is it? Leading you to rely on further hacks to make sure the text stays in the triangle with a nice padding, correct wrapping, and all the other features you get when text is really inside a container.


Could always do <div class="triangle"><span>Hello</span></div> where the div has position: relative and the span has position: absolute. Should work everywhere too.


Yes, that's how you'd get a box to appear over the triangle, but it doesn't really solve any of the containment issues.

Example: http://jsfiddle.net/9pMJS/


Usually I use a :after or :before for the triangle.

#box { position: relative } #box:after {position: absolute; top: -10px; left: 45%; ... }


I vote we change the name from CSS to PWL. PWL is, of course, Puzzle Web Language. This is what I hate about CSS: it's a jigsaw puzzle that must be brute-forced.

The fact that this exists and is lauded as clever rather than being ridiculed for its opaqueness really gets my goat.


The reason this is clever is because CSS wasn't intended to be used to draw shapes. You would use HTML5's canvas element to do that. Instead this shows how you can hack a simple border property to make a DOM element look like a triangle.


Actually I'd use SVG for that, it's even trivial to write:

    <svg width='20' height='10'>
      <path fill='#D94948' d='M0,20h20L10,0'/>
    </svg>
Should be supported pretty much everywhere canvas is, but without the need of scripting to actually get a triangle.


But that's hardly reusable. You'll have to copypaste the (completely nonobvious) markup everywhere you want a triangle. Although it might be possible to use the CSS :before pseudo-element...


More obvious if you use a polygon rather than a path object:

  <svg height=10 width=20>
      <polygon fill=red stroke-width=0 
         points="0,10 20,10 10,0" />
  </svg>
And you can put it in your CSS using a data URI:

  .triangle {
      background: url("data:image/svg+xml;charset=utf-8,<svg height='10' width='20' xmlns='http://www.w3.org/2000/svg'><polygon fill='red' stroke-width='0' points='0,10 20,10 10,0' /></svg>") no-repeat left center;
      width: 20px;
      height: 10px;
  }


I'm more comfortable with the path syntax, and polygons are pretty much the same as a path, except that you would prepend M and append z to the list of points (for certain buggy renderers it might be necessary to put an L inside, too). Paths have handy shorthands for horizontal, vertical and relative movement, though.


If you're more comfortable with it, that's great. To someone who's not already comfortable with it, points="0,10 20,10 10,0" is a lot more obvious than d='M0,20h20L10,0'


SVG has `symbol` and `use` for reusing stuff: http://www.w3.org/TR/SVG/struct.html#SymbolElement


I can't stand the w3 docs sometimes. After reading that section about `symbol`, I still have no clue what it is or how to use it.


What exactly don't you understand? I find the W3C specs fairly well-written, actually.

You declare a symbol in the defs section of an SVG image and you can instantiate it with use. E.g.

  <svg>
    <defs>
      <symbol id='foo'>
        <circle r='5' cx='10' cy='3'/>
      </symbol>
    </defs>
    <use xlink:href='#foo' x='2' y='5'/>
    <use xlink:href='#foo' x='10' y='10' fill='red' stroke='blue'/>
  </svg>
(does not actually work, because namespaces are missing and the symbol likely is missing things like a viewbox, but just to get the general idea across)


If you're still within HTML, is

  <img src='triangle.svg'>
really that much harder than

  <div class='triangle'></div>?




I'm the only one here that although thinks it is a cool presentation fells sad about how a triangle needs to be described as a very broken rectangle?


A lot about CSS is sad.


A lot about CSS is sad indeed. But this demo actually does a good job of explaining a common CSS hack.


yet we have no alternatives for CSS.


I disagree. It would be sad if a triangle couldn't be created in CSS at all.

In fact, I think it's awesome that a triangle can be created from a "very broken rectangle", along with many other hacks that make this simple language quite powerful.


I really hope you're being sarcastic. Sometimes these things have a way of whooshing over my head...


Why would he be when it's mostly cross-browser? It means you dont need to draw the triangle and throw it into a .png or your sprite then deal with all that crap. You have a triangle that you can use to point at things AND you can modify the borders to change the size of that triangle on the fly. Yay.


I'm currently learning CSS, and it really all seems like dirty hacks to me. margin: o auto;? So I can't tell this to just horizontally center itself automatically?

Don't get me wrong, I love dirty hacks, just not if they're forced onto me. I guess in a couple of weeks stockholm syndrome will set in, and I'll love it, but for the beginner, especially if you're moving there from either design (What, I need to hack things to get this typography display right?), or programming (What, I need to learn a whole bag of tricks to get the site to style properly?), CSS seems like that dirty pimp down the street to you. Yeah, he's fabulous, but he always wants you to do tricks for him.


I don't know any developers who like CSS. It's just a thing we have to do.


Really? I started out doing CSS, and I still love it 10 years later. Sure, it has its quirks, but now that we have tools like SASS, it makes CSS so much more fun all over again.


I envy you, then, 'cause I freaking hate it.

SASS and LESS provide really nice language improvements, but they don't fix all the crap about box models and positioning and polyfills and byzantine precedence rules and the necessity for silly hacks like this. It's just too complicated and painful to make things look the way you want them to look, which is the point of CSS. I've gotten pretty good at it and I've come to care a lot about how it works (e.g. this little visualization is a really nice demonstration), but this state of affairs saddens me; I wish I could concentrate on other stuff, and not how to make a goddamn triangle.

(At some level of technical hair-splitting, this isn't per-se CSS's fault and is more general DOM crapiness, but that distinction is largely irrelevant. They're still problems I'm expected to solve with CSS.)


I'm with you. Anyone who says CSS is A-OK doesnt understand it fully or doesnt have the imagination for something better to replace it. It's really the most shite language I've ever had to deal with.

That's the thing though, we have to deal with it. I don't get why there isn't just a complete replacement trending on HN every other month. Sure, it needs browser support and it would forgo a lot of the CSS-specific optimizations baked into the browsers but there has to be a more efficient way to handle the DOM.


I think CSS is A-OK and I believe I understand it fully as I've been using it for most of my career. Most of its "problems" are rooted in bad implementations in browsers or people trying to use it for things it wasn't designed for, not in the spec itself.

But maybe I think this because I don't view it as a language, to me it's more of a configuration file that holds sets of instructions. It's getting closer to a proper language though.

You can have your opinion I suppose, but nearly every web tech I've worked with over the years has had its transitions from good to bad to hated only to end up somehow good again.


Well, margin: auto is how you center things horizontally. What? You want something like align: center instead? Well, that's just semantics. It's a legacy issue built on extending instead of improving.

Here's a fun one, make a div display: inline-block and then use text-align: center on its parent. Why the hell does the div center when the rule is for text? Is it badly implemented or is it badly named? Without reading the actual spec it's a mystery.

I use CSS extensively nearly every day. I learned CSS before IE6 existed. You don't like dirty hacks? I've likely forgotten more dirty hacks then you'll ever be required to know about. Compared to how things started, CSS is a godsend to us today. But I'm not going to yell to you to get off my lawn, because the fun has only just started and you should feel free to join in.

The problems you listed that you have with CSS, you do realize that's mostly because of how browsers implemented CSS and some related technologies right? CSS isn't a dirty pimp, he's actually the guy down the street that knows all about fashion and design but everybody keeps wanting him to build cars.


It's not a hack, margin: 0 auto is how you tell a non-table element to center itself. Sure, there's some oddities to CSS, but if you understand the box model it's not that foreign.


Yeah. But that's just a simple, freaking right triangle. Why all the hoop-jumping?


Note: You only need to specify 3 borders.

Eg. a triangle pointing down:

  .triangle-down {
    border-left: 7px solid transparent;
    border-right: 7px solid transparent;
    border-top: 7px solid #444;
  }


A little more concise:

  .triangle-down {
    border: 1em solid transparent;
    border-top-color: #444;
  }


[deleted]


width and height are automatically 0 if the element is inline (i.e. a span) or absolutely positionrf (which is usually true for these kinds of triangles)


At YOW Australia 2012, Brian Beckman and Erik Meijer gave an entertaining presentation about 'The Story of the Teapot in HTML'. I thought it was going to culminate in a 3d animation of a teapot in a browser using Javascript and CSS triangles, but they didn't get that far.

Anyway, here's a link to the video: http://yow.eventer.com/yow-2012-1012/the-story-of-the-teapot...


This trick is as old as the dHTML. Adding some triangulation algorithms you have a fun 3D ending engine.


Ahhh the hatin' HN crowd. For what it's worth - I've built this bit of CSS over and over but seeing so uniquely presented was great. Thanks for that.


Now animate this using a border with an inner color like this:

http://cssarrowplease.com/


That's essentially doing the same trick twice, only with a slightly larger version that matches the border color of the box and is positioned behind the smaller triangle.


I find it depressing how most of CSS related drawing is basically all just hacks. I saw the same a few weeks ago when someone posted a bunch of different CSS shapes - the code behind it was the most unintuitive stuff. It's like saying - here's a bicycle - now lets get another one and weld it together in some ugly way and make a car out of it. I dont understand why CSS / Browsers have not come far enough to natively support basic shapes? Surely if we can make self-driving cars - rendering things in browsers should be simpler? (yes I am aware of SVG & Canvas - but they dont work everywhere - dont get why the good folks at google , ms & mozilla cant get together and agree that the web shouldnt be full of ugly hacks masquerading as stylesheets).


There shouldn't be any CSS-related drawing. Full-stop. Your analogy is accidentally very accurate, because it's like looking at a car, then a pile of bicycles, and saying "how can I get from A to B". The sane person would go to an auto parts store, get the appropriate parts and build a car as we understand it. The madman would weld two bicycles together, and then complain that it wasn't intuitive to do - bicycles aren't supposed to be used for creating cars. Likewise, CSS is not for drawing shapes: it's for styling things. As you pointed out, we have canvas and SVG for drawing, plus images for things like icons.

As for the compatibility thing, you're coming at it the wrong way. Don't tell Google et al. to support yet another standard for CSS shapes. Let them spend their time implementing SVG and Canvas according to the existing spec. Inventing a new spec not only doesn't solve the problem, it actually re-introduces it.


1) I never mentioned a new spec. 2) " bicycles aren't supposed to be used for creating cars. " - exactly my point.

I think we said the same stuff - came at it from slightly different angles. I´m not advocating yet another standard. Im saying - lets make it easy enough to use the appropriate (and already existing) standards to draw - rather than be at the mercy of a seemingly prehistoric styling system. My point with google et al was - get together and agree to a way to do simple things like images - the same way across browsers.

Does that help clarify?


Sweet. Thanks for making this. It'd be awesome if you could extend the animation and show examples of complex shapes you could make with triangles.


It'd be even more awesome if you could actually make complex shapes with these triangles.


You can. It just requires absolute positioning. I can't see why you'd want to though, it's not hard enough to be fun or useful enough to be work.


And if you try this, you will usually get light segments in places where triangles forming some shape meet (due to antialiasing and overall hackery).



I wish all CSS was described this way... Thanks!


Very cool!

I always knew how it worked but it was nice to see the animation play out.


Somehow I'm tempted to click the "report abuse" button.


I had no idea. Thanks for the very cool animation/explanation. A+


Honestly, why is there no basic web drawing app out there that exports to CSS? Should be doable and hence done.



> Should be doable and hence done.

OK, that's it everybody. Trying to do something? Is it done yet? Nope? Pack it in. All the things have been done.


So do it.


I always sort of wondered about this, but I never got around to investigating it. Thanks for the lesson.


Does this mean if you create a 100px high triangle, it has 100px of invisible padding on top?


No. If you take the example animation, you can set border-left-color and border-right-color to transparent, and set border-top-width to 0. This will place the triangle in a bounding box of the correct width and height.


Simple, elegant and to the point. Give me more stuff like this.


Designer: "wow this is cool"

HN reader who's not a designer: "don't like, bleh CSS, should SVG, used to do that in VIM, TIMTOWTDI" and other similar useless rants missing the point.


the problem is people seeing and sharing this, thereby giving it some sort of authority. It's possible and still a dumb idea. Yet another thing front end coders have to encounter and fix after somebody else applies these kinds of embarrassing hacks.


Except there's nothing to "fix". That's one way to do triangle in CSS, it's not better or worse than another one, and it's been known for ages. The cool thing here is the visualization, not the technique itself.


Um, it works. It even works following the rules that have been in place for years. Why would you have to "fix" it?


Is this a hack? Yes. Hacks are replaced by standardized and better approaches (especially when better approaches are available now. "Fixing" this means removing it in code in place of a more logical approach. Where a triangle is really a triangle, not a rectangle with no dimension.

Part of web work is knowing immediately what you're dealing with. dimensionless rectangles that show up as triangles is a layer of complexity (hack) that disrupts flow.

Get it?


Well crap, I guess I just don't get it.

I suppose I'll understand once I realize what you mean by "fixing" is actually "replacing". Specifically with your preferred method of accomplishing the same thing.

You aren't one of those programmers that can't help themselves in "fixing" everybody else's code that comes across your desk because they didn't do it the way you would, regardless of whether it works or not? I mean, the attitude I'm sensing in your text suggests that, but I'm sure you're a better person than that in real life.


"fixing everybody else's code that comes across your desk because they didn't do it the way you would"

that's the real world of design and collaborative environments. Branding, code quality, standards they all start with setting a direction that makes sense in order to improve efficiency across multiple disciplines and experience levels.

Hackey fixes have always been available. Instead of using h3 tags you can use b tags and scale them up to a particular font size.

Even when something works, you have collaboration and reputation to operate by. Case in point: Somebody actually had to create an animation to explain what the hell is going on with this hack to people who already know html and css, whereas with a unicode character or SVG you wouldn't have to have meta instructions. You could say good code or technique often requires no explanation.

that's what I'm trying to get it.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: