2

I would like to get a specific layout using CSS, as follows, and I'm not sure if it's possible. There's some text inside a div that is centered. Underneath, there is another div with text inside; what I'd like to do is to right-align this text so that its right edge is flush with the right edge of the text above it.

Using CSS, I have no idea how to do this. Clearly the following approach will not work, because the sub-header will right-align to the container. But is there any trick to accomplish the alignment I want?

<div style='text-align: center;'>This is some headline text</div>

<div style='text-align: right;'>Sub-header text</div>

Note: Strong preference is for straight CSS (no Javascript if possible).

Note #2: I'm not stuck with the above HTML. I can use any markup that accomplishes the described alignment.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260

1 Answers1

6

@thirtydot no, I'm happy with any HTML that will accomplish the alignment.

Try this then: http://jsfiddle.net/thirtydot/nU9Cj/

<div style='text-align: center'>
    <span style="position: relative">This is some headline text
        <span style='position: absolute; top: 100%; right: 0; font-weight: bold'>Sub-header text</span>    
    </span>
</div>

You probably want to add some padding-bottom to the div, to make up for the height lost by the subheader being absolutely positioned.

thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • I just had this exact problem, and greatly appreciate the solution. One extra note: the position:relative span needs to not be a div, because a div expands to take up extra horizontal room, shoving the subheading off to the right side of the screen. (Or at least, the position:relative element needs to not be display:block.) – PotatoEngineer Sep 20 '18 at 22:26