简体   繁体   中英

Left-align one element and center-align another, but have centered element pushed by left element

I am currently using flex and I assume it is necessary, but I am open to all CSS solutions.

I have a bar with some elements on the left. This is done with flex: 0 0 auto; on this element group and flex: 1 1 auto; on an empty element after it.

I need to put another set of elements in the center of this bar (not the center of the remaining space). If the first set of elements weren't there, I could do flex: 1 1 auto on the left and right of the centered element with flex: 0 0 auto; .

But now I need to combine these so the left element stays on the left and the middle element stays in the middle, but I also need the left element to push the middle element to the right (therefore making it no longer centered) if they touch.

Edit: I should mention that the widths of both elements are dynamic. I do know heights, but it would be better not to need them.

图

Something like this?

HTML

<body>
    <aside>Left</aside>
    <main>Right</main>
</body>

CSS

* {
    margin: 0;
    padding: 0;
}

main {
    width: 1000px;
    height: 500px;
    background: cyan;
    margin: 0 auto;
}

aside {
    float: left;
    width: 200px;
    height: 500px;
    background: magenta;
}

Here's a solution that uses absolute positioning and requires the left block's width to be explicitly set. Essentially, absolute positioning takes the block out of the flow and to make sure that the left and right blocks do not overlap, the left margin is set on the right block that is the size of the left block's width.

Here's a fiddle: http://jsfiddle.net/4RqEr/ . (Resize the preview window to see the effect).

HTML:

<div class = "container">
    <div>left</div>
    <div>Pushed to Right</div>
</div>

CSS:

* {
    margin: 0;
    padding: 0;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

body {
    padding: 10px;
}

.container {
    background-color: #ccc;
    position: relative;
    text-align: center;
    overflow: hidden;
}

.container > div:first-child,
.container > div:nth-child(2) {
    padding: 10px 20px;
    background-color: #fA5858;
    color: #fff;
    text-transform: uppercase;
    font: 15px/1 Sans-Serif;
}

.container > div:first-child {
    position: absolute;
    left: 0;
    width: 100px;
}

.container > div:nth-child(2) {
    display: inline-block;
    background-color: #5882FA;
    margin: 0 100px;
    white-space: nowrap;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM