CSS Nugget #4: Setting box arrow on a div

Every popover element has a little arrow. We see this pattern all over when we click on a button and a div pops up. Here is an example of this UI pattern – Box arrow.

Box arrow

In this post, I will walk through how this works. Here is a CodePen for this post.

The HTML is only a div containing some text.

<div class="box">
  This is me, Vijay Thirugnanam.
</div>

The CSS for the div is pretty simple.

.box {
  position: relative;
  width: 200px;
  padding: 10px;
  background-color: steelblue;
  color: white;
}

The only tricky style in the div is its positioning. It is set to relative. This implies that we want to position something absolutely within the div. The element that we want to position absolutely is the arrow. To make the arrow, we use the :before pseudo element.

CSS for the Box Arrow

The CSS for the Box Arrow is the trickiest part.

.box:before {
  content: '';
  position: absolute;
  width: 0px;
  height: 0px;
  right: 10px;
  bottom: -16px;
  border-style: solid;
  border-width: 16px 8px 0px 8px;
  border-color: steelblue transparent transparent transparent;
}

The :before element has an empty content and it is positioned absolutely. It is pushed 10 pixels to the right and 16 pixels further from the bottom. Most importantly, the width and height of this element is 0. The arrow comes from styling the border for the element.

We split the border properties. Set the border-style to solid. The border-width takes 4 values: top, right, bottom, left. The top is set to 16 pixels and bottom is 0 pixels. This gives a triangle shape. The left and right border should be set to some value and forms the base of the triangle.

Another important property to set is the border-color. Only the top border has the steelblue colour. The rest of the border has a transparent color.

When you are making this sort of box arrow, feel free to play with the border-width and border-color properties. The border-widthgives the dimensions of the triangle as well as the direction of the arrow. Whereas the border-color property gives the triangular shape.

Related Posts

Leave a Reply

Your email address will not be published.