Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center element until it meets an obstacle

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

enter image description here

small screen

enter image description here

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

like image 528
skyisred Avatar asked Sep 05 '14 22:09

skyisred


3 Answers

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';
}
like image 31
Rick Hitchcock Avatar answered Oct 24 '22 09:10

Rick Hitchcock


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

like image 138
Oriol Avatar answered Oct 24 '22 09:10

Oriol


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;
    }
}
like image 1
kornieff Avatar answered Oct 24 '22 10:10

kornieff