A possible solution may be as follows:
HTML
<div class="red"> <div class="blue"> </div> <div> <div class="centered"> Centered Container of fixed width </div> </div> <br/> The pink and light geen background sides mark centers of the containers. These centers should align until green container meets blue container.
CSS
.red { height: 100px; text-align: center; border: 3px solid red; position: relative; background: linear-gradient(to right, #ffffff 50%,#ffe2e2 50%,#ffe2e2 100%); } .blue { background: blue; width: 150px; height: 100%; } .centered { display:inline-block; height: 50px; border: 3px solid green; position: absolute; left: calc(50% - 73px); width: 140px; top: 0; background: linear-gradient(to right, #ffffff 50%,#CDF2DD 50%,#CDF2DD 100%); }
JQuery
var width = 0; var sizeBlue = $(".blue").width(); $(window).resize(function() { var offset = $(".centered").offset(); var right = $(window).width()-sizeBlue; if (offset.left <= sizeBlue){ $(".centered").css("left",sizeBlue); width = $(window).width()-sizeBlue; } else if (right > width){ $(".centered").css("left","calc(50% - 73px)"); } });
Check out this jsfiddle link for how it works.
Hope this is helpful!
source share