panthro panthro - 1 year ago 94
CSS Question

Left and center align items in a div?

How can I layout the contents of a div with one element centred and the other aligned left.

I've tried flexbox - not possible without adding a hidden 3rd element and justifying content.

I've also tried text align on parent but then everything is aligned in one way (centered or left).

HTML:

<div class="container">
<div class="left">
I'm left aligned
</div>
<div class="center">
I'm center aligned
</div>
</div>


Edit:

Im aligning the divs themselves, and centered relative to parent.

Answer Source

you can use flex and :after element for the hidden element:

.container {
display:flex;
justify-content: space-between;
border:1px solid #000;
}
.container:after {
content:" ";
display:block;
flex:1;
}
.left,.center {
border:1px solid #0F0;
flex:1;
text-align:center;
}
<div class="container">
    <div class="left">
        I'm left aligned
    </div>
    <div class="center">
        I'm center aligned
    </div>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download