I have a fieldset containing a legend that has a ::before pseudo-element and I want this pseudo-element to be positioned above the legend without affecting the legend's position.

HTML:

<fieldset>
    <legend>THE TEXT</legend>
</fieldset>

CSS:

legend {
    padding:0 14px;
}

legend::before {
    content:'BEFORE ';
    color:red;
}

JSFiddle demo

I tried adding legend::before { vertical-align:super } but it puts the legend element down like this:

JSFiddle demo superscript (without success)

Any idea's would be welcome to accomplish this.

2

There are 2 answers

2
Jackson On

Use position: absolute; on the pseudo element like this:

legend {
  padding: 0 14px;
  position: relative;
}

legend::before {
  content: 'BEFORE';
  color: red;
  position: absolute;
  top: -20px;
}
<br>
<fieldset>
  <legend>THE TEXT</legend>
</fieldset>

EDIT:

If you would like the text to appear beside the legend then use the left attribute.

See updated jsFiddle

2
Daan On

I just found a solution for my own question, adding display:block; and float:left to the ::before makes it works as I want. I could then add margins to the element as I wanted without affecting the legend:

legend { padding:0 14px; }

legend::before {
    content:'BEFORE';
    color:red;
    float:left;
    margin-top:-5px;
    padding-right:5px;
}

JSFiddle demo