How can the pseudo element detect the height of the non-pseudo element?

Randomblue picture Randomblue · Sep 19, 2011 · Viewed 15.4k times · Source

Please see http://jsfiddle.net/ZWw3Z/

<p>Text text text text text text text...</p>
p {
    background-color: blue;
}

p:before {
    content: '';
    position: absolute;
    width: 10px;
    height: 100%;
    background-color: red;
}

Essentially, the height of the pseudo element is too big. I want it to have the same height as the p element. How can I do that?

Answer

user926352 picture user926352 · Sep 19, 2011

To future readers, the effect was to have a bar appear over text on the left-hand side. To accomplish this, the OP was using position: absolute; on the psuedo element (p:before).

The error OP was encountering was because the psuedo-element was treating the <body> as it's relative position point - to fix, simply set position: relative; on the <p> tag.

p {
  position: relative;
  background-color: blue;
  padding-left: 10px;
  /* change the padding to something larger 
  than the width of the :before element to 
  add spacing for text
  */
}

p:before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  width: 10px;
  height: 100%;
  background-color: red;
}
<p>text... text...</p>