tags:

views:

142

answers:

2

I'm trying to center a heading (with variable width) and have the underline running from the left hand edge of the page to the end of the text. Unless I'm missing something, there doesn't seem to be an easy way of doing this! The closest I've come to what I want is:

<style type="text/css">

#wrapper1 {
margin-right: 50%;
border-bottom: 4px solid red;
}

#wrapper2 {
text-align: center;
position: relative;
left: 50%;
}

h1 {
display: inline-block;
margin: 0 auto;
border-bottom: 4px solid red;
}

</style>

<div id="wrapper1"><div id="wrapper2"><h1>Centered.</h1></div></div>

This way, the text is centered with a border acting as an underline, and the border on wrapper1 extends from the left hand edge to the center. BUT, because the heading is within the wrapper, and the border on the wrapper is outside of the content, the wrapper border is below the heading border.

Any suggestions gratefully received - this is driving me mad!

+2  A: 

Try removing both the padding-bottom and margin-bottom on both wrappers (set to 0), then add it back in on the inner one only until it looks right.

OK, I had a go, and this works for me. I had to put position relative on both wrappers, which then allows you to push the inner wrapper down a couple of pixels from it's original location.

<html>
<head><title>test</title></head>
<body>
<style type="text/css">

#wrapper1 {
margin-right: 50%;
margin-bottom:0;
padding-bottom:0;
border-bottom: 4px solid red;
position:relative;
}

#wrapper2 {
text-align: center;
position: relative;
left: 50%;
margin-bottom:0;
padding-bottom:0;
position:relative;
top:4px; /*The width of the border doing the underlining*/
}

h1 {
display: inline-block;
margin: 0 auto;
border-bottom: 4px solid red;
}

</style>

<div id="wrapper1"><div id="wrapper2"><h1>Centered.</h1></div></div>

</body>
</html>
Andrew M
Yep, that works as well. Seems I needed to look more closely as the inner wrapper!
Mike
+2  A: 

In your #wrapper2:

bottom: -4px;

Will make it move 4 pixels downwards to overlap the other line.

(Tested in Safari, works)

Pindatjuh
Bingo! I'd tried adding and removing 4px from all over the place, but not there! Thanks.
Mike
Faster than me and simpler too I think.
Andrew M
The padding/margin wasn't needed, your answer is exactly equal since `bottom: -4px` and `top: 4px` are synonyms. Though I prefer `bottom`, because it implies you want it to move downwards, from below.
Pindatjuh