Edit: I ended up going for Center and right align flexbox elements Michael_B's answer Method #2
So I've got a container in which there are two elements, a red and a green box (width not fixed). I would like the green box to be centered in the container as long as it can. And when the red box is in the way, then the green box just sits next to it.
The only way I know how to do that is if the red box is set as position: absolute
but the issue is that when the container becomes too small, then the green box overlaps the red one.
I am only supporting modern browsers (no IE) so flexboxes and other new stuff is welcome.
Thanks.
.wrapper {
width: 600px;
height: 100px;
text-align: center;
position: relative;
border: 5px solid black;
}
.wrapper+.wrapper {
margin-top: 20px;
}
.wrapper:nth-child(2) {
width: 500px;
}
.wrapper:nth-child(3) {
width: 410px;
}
.align-left {
display: inline-block;
position: absolute;
left: 0;
background-color: red;
width: 100px;
height: 100%;
z-index: 0;
}
.centered {
display: inline-block;
background-color: green;
width: 300px;
height: 100%;
// so the overlap is more visual
z-index: 1;
position: relative;
}
<div class="wrapper">
<div class="align-left"></div>
<div class="centered">
</div>
</div>
<div class="wrapper">
<div class="align-left"></div>
<div class="centered">
</div>
</div>
<div class="wrapper">
<div class="align-left"></div>
<div class="centered">
</div>
</div>