Robert Strauch
Robert Strauch

Reputation: 12876

Left-align a <div> to a centered <div> with CSS

I'm trying to create a web page with several <div> blocks styling them with CSS according to the following diagram. However I have no clue how to get this done. I have tried both variants as suggested by the answers (https://stackoverflow.com/a/26599439/478406 and https://stackoverflow.com/a/26598329/478406) but I think I'm missing something.

enter image description here

Upvotes: 0

Views: 96

Answers (2)

Gary
Gary

Reputation: 1179

The HTML and CSS below should do what you want, if I understand what you're asking correctly.

Note that display:inline-block allows the two div elements to sit next to each other, so you can set their text-align independently. Also, because of the inline-block property the elements will wrap when the screen size becomes smaller.

http://jsfiddle.net/k6y8asbk/

.message-text{
    text-align:left;
    display:block;
}

.some-text,
.my-list{
    display:inline-block;
    text-align:left;
    vertical-align:top;
}

.my-list{
    text-align:center;
}

ul{
    margin-top:0px;   
}

<div id='message-container'>
    <div class='message-text'>Message Text</div>
    <div class='some-text'>Some text</div>
    <div class='my-list'>
        <ul>
            <li>item 1</li>
            <li>item 2</li>
            <li>item 3</li>
        </ul>
    </div>
</div>

Upvotes: 1

steve.n
steve.n

Reputation: 88

I think to accomplish something like this, you'd need to wrap everything in a container with text-align: center, then wrap the message in a span with display: inline-block and position: relative. This will allow the first line of text to determine the width of the block-level element, while still being centered in the outer container. Since we set position to relative, we can now create a child element to be aligned to the left edge of the first line with a position: absolute.

Here is a jsfiddle as a proof of concept

Noe: Absolute position takes the element out of the stack order, so anything below will collapse up. This means that if the first line is too short, the second line will overlap with the list (but that would be an issue regardless, as the list is supposed to be centered). If the list doesn't need to be centered perfectly, you could include it inside the child element that is positioned absolute and adjusted the list's positioning as needed.

Upvotes: 1

Related Questions