8

My paragraph has a height/line-height of 50px and text-align: center, which centers the text. But p:before is causing it to increase in height/line-height, causing the text to bump down. I want both p and p:before to be vertically centered.

http://jsfiddle.net/MMAUy/

<p>Hover This</p>

p {
    background: red;
    text-align: center;
    height: 50px;
    line-height: 50px;
    font-size: 14px;
}

p:hover:before {
    content: "icon";
    display: inline-block;
    margin-right: 10px;
    font-size: 3em;
}

The text length varies so I don't think i can just use position: absolute for the icon...

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
Sunny
  • 2,232
  • 7
  • 24
  • 36
  • Interesting question. What varies in length? The text on hover, or the actual text before hover? – Josh Crozier Oct 17 '13 at 23:55
  • I was just saying I can't use position: absolute for the icon because the text won't always be the same, and i need the icon right next to the text. – Sunny Oct 18 '13 at 00:01
  • Check out this fiddle, http://jsfiddle.net/MMAUy/1/ I removed the height. Looks like the pseudo-element is adding some height to the box... Any ideas? – Sunny Oct 18 '13 at 00:07

3 Answers3

12

The reason this occurs, is because line-height is being inherited by the :before elements, which is also an inline-block element.

You could solve this by floating the :before content, thus removing it from the flow, rendering it unaffected by the line-height.

jsFiddle here

HTML

<div>
  <p>Hover This</p>
</div>

CSS

div {
    background: red;
    height: 50px;
    line-height: 50px;
    font-size: 14px;
    text-align:center;
}

div:hover p:before {
    content: "icon icon icon icon";
    margin-right: 10px;
    font-size: 42px;
    float:left;
}
p {
    display:inline-block;
    margin:0px;
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Good idea with the float. I still wonder if there's a way to accomplish this without adding additional markup? – Sunny Oct 18 '13 at 00:36
9

It's really simple. You should give

vertical-align: top;

to the :before element.

Your updated jsFiddle: http://jsfiddle.net/Pz7vF/

0

Something that worked for me is using !important, as long as you're not already using it in the element.

element {
  line-height : 110%;
}

element::before {
  content : "HI";
  line-height : 40px !important;
}
Raid
  • 747
  • 8
  • 17