Modifying the height and width of CSS pseudo element content

If you want to add an image before or after an html element, you most often use the pseudo-elements :after and :before. For example, when you want to add an image before a link, you can write it like this:

a:before {
url(image.png);
}

But you can’t control the width or height of this image this way. If it is absolutely necessary for you to control the dimensions of this pseudo element, the following is what you do:

  1. Move the image to the background image property.
  2. Define the height and width of the pseudo element. These are the dimensions of the image.
  3. Make the content an empty string.
  4. Give the background-size the same dimensions as the image.

This is how you would do it in CSS:

a:before {
background-image: url(image.png);
background-size: 40px 40px;
display: inline-block;
width: 40px;
height: 40px;
content: "";
}

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.