0

While following this tutorial, this piece of code is claimed to draw an arrow, but was never explained properly.

.tooltip:hover:before{
    border: solid;
    border-color: #333 transparent;
    border-width: 6px 6px 0 6px;
    bottom: 20px;
    content: "";
    left: 50%;
    position: absolute;
    z-index: 99;
}
<div class="tooltip">Sample text</div>

Can anybody please explain how's it doing that?

Omar Ali
  • 8,467
  • 4
  • 33
  • 58
sherlock
  • 2,397
  • 3
  • 27
  • 44

1 Answers1

2

The trick is in the border color and width. Imagine a box with zero height and width, just the borders, those borders are meeting in the exact center. If you draw one border with a color (#333 in this case) and leave the rest as transparent, you get an arrow.

The technique is explained further on CSS Tricks: https://css-tricks.com/snippets/css/css-triangle/#article-header-id-2

Omar Ali
  • 8,467
  • 4
  • 33
  • 58
  • I got the technique from the link. Many thanks! But why it was needed to use `before` and `after` pseudo-elements? – sherlock Jan 14 '17 at 18:52
  • @Holmes.Sherlock because it creates a pseudo-element to draw the border inside it. It's equivalent to having a div/span next to your element and use it to draw the border. The only different is that this method uncluttered the DOM. – Omar Ali Jan 14 '17 at 18:54