我正在尝试制作一个页面容器,该容器的左侧(容器内部)具有导航栏。当外部页面的宽度大于容器的宽度时,我只希望导航栏向左延伸一定的大小,而其余的容器内容保持不变并停留在外部页面的中间。

为了说明我的想法,以下是之前和之后的图像,黑色表示外页,蓝色表示页面容器,粉红色的leftnav,绿色表示容器的其余部分。

这也是我正在编写的代码的一般结构。 jsfiddle链接包含一些css以获得详细信息。

<div id="page">
<div id="container">
    <div id="leftCol">
        LEFT
    </div>
    <div id="rightCol">
        RIGHT
    </div>
</div>




https://jsfiddle.net/6L1zrj6e/1/

当前,我的容器具有固定的宽度和自动边距,以使其居中。使用当前的布局,我想达到的目标甚至可能吗?我需要将leftnav div移出容器吗?

最佳答案

您可以尝试以下操作:Full screen example

jsFiddle

HTML:
(从容器中取出leftCol)

<div id="page">
    <div id="leftCol">
            LEFT
        </div>
    <div id="container">
        <div id="rightCol">
            RIGHT
        </div>
    </div>
</div>


JS :(在页面大小调整和加载时更新宽度)

$(window).on('resize', function(){
    var containerWidth = 980;
    var pageWidth = $(window).width();

    var tempW = Math.max(0, pageWidth-containerWidth) / 2;
    tempW  += 200;
    var w = Math.min(tempW, 360); // 360 = max width
    var l = Math.max(0, tempW - w);
    $('#leftCol').css({'width': w+'px', 'left': l+'px'});
}).resize();


CSS :(已删除浮点,使用leftCol的绝对位置)

#page{
    background-color: purple;
    position:relative;
}
#container {
    background-color: blue;
    width: 980px;
    height: 300px;
    margin: 0 auto;
}
#leftCol {
    position:absolute;
    top: 0;
    left: 0;
    background-color: red;
    height: 300px;
    width: 200px;
}
#rightCol {
    padding-left:200px;
    background-color: green;
    height: 300px;
    width: auto;
}

07-28 01:58
查看更多