I know this has already been decided, and pixels have been requested. However, I just wanted to share something ...
Partially underlined text elements can easily be achieved with display:table or display:inline-block
(I just don't use display:inline-block , because, you know, an uncomfortable 4px difference).
Text elements
h1 { border-bottom: 1px solid #f00; display: table; }
<h1>Foo is not equal to bar</h1>
Centering , display:table makes it impossible to center an element using text-align:center .
Let it work with margin:auto ...
h1 { border-bottom: 1px solid #f00; display: table; margin-left: auto; margin-right: auto; }
<h1>Foo is not equal to bar</h1>
Well , it's nice, but it's not partial .
Since bookcasey has already been introduced, pseudo-elements are worth the gold.
h1 { display: table; margin-left: auto; margin-right: auto; } h1:after { border-bottom: 1px solid #f00; content: ''; display: block; width: 50%; }
<h1>Foo is not equal to bar</h1>
Offset , underline is aligned to the left right now. To center it, just push the pseudo-element half its width ( 50% / 2 = 25% ) to the right.
h1 { display: table; margin-left: auto; margin-right: auto; } h1:after { border-bottom: 1px solid #f00; content: ''; display: block; margin-left: 25%; width: 50%; }
<h1>Foo is not equal to bar</h1>
... like davidmatas , using margin:auto is sometimes more practical than manually calculating the margin -offset.
So, we can align the underline left, right, or in the center (without knowing the current width ) using one of the following combinations:
- Left :
margin-right: auto (or just leave it) - Middle :
margin: auto - Right :
margin-left: auto
Full example
.underline { display: table; margin-left: auto; margin-right: auto; } .underline:after { border-bottom: 1px solid #f00; content: ''; display: block; width: 50%; } .underline--left:after { margin-right: auto; } .underline--center:after { margin-left: auto; margin-right: auto; } .underline--right:after { margin-left: auto }
<h1 class="underline underline--left">Foo is not equal to bar</h1> <h1 class="underline underline--center">Foo is not equal to bar</h1> <h1 class="underline underline--right">Foo is not equal to bar</h1>
Block Level Elements
This can easily be accepted so that we can use block level elements. The trick is to set the height of the pseudo-elements to the same height as its real element (just height:100% ):
div { background-color: #eee; display: table; height: 100px; width: 350px; } div:after { border-bottom: 3px solid #666; content: ''; display: block; height: 100%; width: 60px; }
<div></div>
yckart May 20 '16 at 5:05 a.m. 2016-05-20 05:05
source share