Search code examples
css-floatvertical-alignmentcssalignment

H1 on the left, "buttons" on the right, vertically aligned


I'm trying to display on one line:

  • a H1 element aligned to the left of the containing box
  • several "buttons" (A elements here) aligned to the right of the containing box
  • all being on the same baseline

Is it possible to do this with minimal markup (i.e. no wrapping elements) and without having to set precise heights, line-heights, margin-tops, etc.

<div id="block1">
    <h1>What a great title</h1>
    <a href="javascript:void(0)">This link can kill you</a>
    <a href="javascript:void(0)">Click if you dare</a>
</div>

The fiddle here shows what I feel are two incompatible directions (inline-blocks and you can't align to the right vs. float right and you can't align vertically): http://jsfiddle.net/GlauberRocha/bUsvX/

Any idea?


Solution

  • You have a potential problem with that layout - what if your H1 is too long and so are the buttons? They will run in to each other. Because of this, no simple CSS will do - CSS doesn't do magic like that - it would have to imply some sort of solution to the above problem.

    However, what you want can simply be accomplished using absolute positioning:

    <div style="position: relative;">
        <h1 style="position: absolute; left: 0; top: 0">What a great title</h1>
        <div style="position: absolute; right: 0; top: 0; text-align: right">
            <a href="javascript: void(0)">This link can kill you</a>
            <a href="javascript: void(0)">Click if you dare</a>
        </div>
    </div>
    

    If you are really afraid that the header and the anchor container might run in to each other depending on generated content, you can use CSS max-width and overflow properties to restrict their containing boxes to some sensible values. The overflowing content will be hidden but at least the layout will not break visually. I assume the following modification of the above code (pardon the duplicate) would serve the purpose:

    <div style="position: relative;">
        <h1 style="position: absolute; left: 0; top: 0; max-width: 50%; overflow: hidden">What a great title</h1>
        <div style="position: absolute; right: 0; top: 0; text-align: right; max-width: 50%; overflow: hidden">
            <a href="javascript: void(0)">This link can kill you</a>
            <a href="javascript: void(0)">Click if you dare</a>
        </div>
    </div>
    

    To round off, you cannot achieve this using a straightforward CSS property combination, because with CSS (and HTML), content flows from left to right and top to bottom, or it becomes absolutely- or fixed- positioned which interrupts the flow. Anyhow, it does not want to remain on the same line, and you as the layout designer are left with resolving ambiguities such layout would introduce, such as what to do when the two trains running from each direction front-collide with each other :-)