Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a shape using a :before pseudo element in CSS

Tags:

html

css

So I've got some h3 tags that I want to prepend with a simple red box. I would have thought something like

h3:before {
    width: 20px;
    height: 20px;
    background: #9B191D;
}

But I actually also have to add a

position: absolute

in order to get a shape to show up, and in that case the following text becomes obscured. So currently I'm doing the following, and I really don't like it

h3:before {
    background: #9B191D;
    position: relative;
    content: "..";
    color: #9b191d;
}

but it works. Does anyone know how I can get a shape with given dimensions to show up without using position:absolute?

like image 860
Csteele5 Avatar asked Dec 10 '22 19:12

Csteele5


1 Answers

By default, a pseudo element's display is inline. You can't set the width/height of a strictly inline-level element, therefore you should change the display to inline-block.

In doing so, you don't have to resort to absolute positioning in order to change the dimensions of the element.

h3:before {
  content: '';
  display: inline-block;
  width: 20px;
  height: 20px;
  background: #9B191D;
}
<h3>Some header</h3>
like image 184
Josh Crozier Avatar answered Jan 05 '23 00:01

Josh Crozier