How to make an x (close icon) in CSS CSS

You don't need use an image or icon library to make a close icon. Here is how to make an x (close icon) in CSS. You only need to create 1 element in HTML which we can then use to make an x with CSS.

<a href="#" class="x">
</a>

Here I have created an anchor a tag and assigned it a class of "x". This class or id name can be anything you want but I've chosen x for simplicity.

Now we can use the ::before and ::after pseudo elements to create the 2 lines of the x (close icon).

First, we'll have to set the content property of both pseudo elements to an empty string because the content property is required to display pseudo elements but we don't actually want to insert text content.

Next, we'll give both pseudo elements display: block;, some width, height, a background color, border radius and a negative top margin equal to the height to place one directly on top of the other.

.x::before,
.x::after {
  content: "";
  display: block;
  margin-top: -3px;
  width: 20px;
  height: 3px;
  background: #000;
  border-radius: 1px;
}

That creates the 2 lines and stacks them together but now we need to angle each line in a different direction to make an x shape. We can rotate each line with transform: rotate();. One line needs to be rotated -45deg and the other needs to be rotated 45deg. I have also included the webkit and ms prefixes to ensure compatibility.

.x::before {
  -webkit-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
}
.x::after {
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

Here is the x (close icon) we've just created with this code:

If you want thicker lines for your x icon, just increase the height property of the pseudo elements and make sure to also update the top margin of the pseudo elements to be the same (but negative) as the new height.

Similarly, if you want thinner lines for your x icon, just decrease the height and top margin of the pseudo elements making sure they are set to the same value with the top margin being negative.

For a larger or smaller x icon, increase or decrease the width property of the pseudo elements.

If you want to make an animated menu icon that turns into an x icon when clicked, read Animated hamburger menu icon to x (close icon) in CSS.

Thanks for reading.
Ryan

Published on 17 Jul 2022