固定宽度的中间 div 和它两侧的两个弹性宽度 div



我正在尝试创建一种排列方式,即div中有三个div填充页面的100%宽度。中间的div 将具有固定的宽度,两个外部div 将分别占用剩余空间的 50%。这可以使用CSS实现吗?

我已经设置了一个小提琴,它不起作用,http://jsfiddle.net/6y5hn/我尝试使用以下代码来实现这一点:

<div id="outerbox">
    <div id="leftbox">(elastic width) This should occupy all the space in the grey box to the left of the red box</div>
    <div id="centerbox">(fixed-size) should be in the center of the grey box</div>
    <div id="rightbox">(elastic width) This should occupy all the space in the grey box to the right of the red box</div>
</div>

使用 CSS:

#outerbox {
    background-color:gray;
    margin-top:50px;
    width:100%;
    height:200px;
}
#centerbox {
    background-color:red;
    margin-left:auto;
    margin-right:auto;
    float:left;
    height:100px;
    width:300px;
}
#leftbox {
    background-color:yellow;
    height:300px;
    float:left;
}
#rightbox {
    background-color:pink;
    height:300px;
    float:left;
}

詹姆斯

不确定仅使用 CSS 是否可以实现这一点,但这里有一个方便的 JavaScript 代码片段,可以帮助您更有效地管理固定和基于百分比的页面宽度:

function resize() {
    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
    viewportwidth = window.innerWidth,
    viewportheight = window.innerHeight
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
    viewportwidth = document.documentElement.clientWidth,
    viewportheight = document.documentElement.clientHeight
}
// older versions of IE
else {
    viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
    viewportheight = document.getElementsByTagName('body')[0].clientHeight
}
}

然后,可以在页面加载以及页面大小调整时调用 resize() 函数。所以像这样:

<body onload="resize()">

从这里,由于您有计算出的页面宽度,因此您可以相应地调整各个div的大小:

document.getElementById("leftbox").style.width = (viewportwidth - 300)/2 + "px";
document.getElementById("rightbox").style.width = (viewportwidth - 300)/2 + "px";
document.getElementById("centerbox").style.width = 300 + "px";

centerbox保持 300 像素的固定值,而 leftboxrightbox 的宽度等于屏幕宽度减去 300 像素,除以 2。

width:calc(50% - 150px);添加到#leftbox#rightbox(150px = 中心框宽度的一半)

http://jsfiddle.net/6y5hn/2/

浏览器支持:http://caniuse.com/calc

只需使用固定宽度的浮点数

#fixed{float:left;width:360px;background-color:green;height:100%;color:yellow;}
#elastic{background-color:#ddd;height:100%;color:grey;}

http://jsfiddle.net/am46bm43/

最新更新