There are two elements inside a container - one (blue) needs to stay to the left, and the other one (green) is centered relative to the outer red. However, if the screen is small enough, the centered container(green) cannot overlap with the container on the left(blue), it should always stay to the right of the blue. Any ideas how this can be accomplished? If not with css, then may be with js?
large screen
small screen
So far i got:
Fiddle
<div class="red">
<div class="blue">
texttexttexttext
</div>
<div class="centered">
Centered Container of fixed width
</div>
</div>
.red {
height: 100px;
text-align: center;
border: 3px solid red;
position: relative;
}
.blue {
background: blue;
height: 100%;
float: left;
}
.centered {
display: inline-block;
border: 1px solid green;
position: absolute;
left: calc(50% - 70px);
width: 140px;
top: 0;
}
This centers the green container, but it overlaps with the blue on smaller screen.
Edit: added some center markings to easily see the centers
If the blue box should have a flexible width, I think the only solution is to use JavaScript.
Here's a fork of your fiddle, which changes the classes to ids and adds a window.onresize event:
http://jsfiddle.net/rf0zLpcs/
window.onresize= function() {
var blue= document.getElementById('blue');
var red= document.getElementById('red');
var centered= document.getElementById('centered');
blue.style.width= Math.min(150,(red.offsetWidth-centered.offsetWidth)/2)+'px';
}
Using JavaScript,
var blue = document.getElementById('blue'),
red = document.getElementById('red'),
centered = document.getElementById('centered');
window.onresize = function() {
centered.style.left = Math.max(
blue.offsetWidth,
(red.clientWidth-centered.offsetWidth) / 2
) + 'px';
}
Demo
Looks like this is something that can be used in page header with items on the side and title in the middle. So, I took a very different and simpler approach. When there is not much width, viewport centering does not look good. Use media query to switch between centering mode. Fiddle Demo
#main {
position: relative;
overflow: hidden;
text-align: center;
}
#center {
position: absolute;
display: inline-block;
left: 50%;
transform: translateX(-50%);
}
@media (max-width: 500px) {
#center {
position: static;
transform: none;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With