gpt4 book ai didi

css - 固定宽度的中间 div 和它两侧的两个 flex 宽度的 div

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:31 25 4
gpt4 key购买 nike

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

我已经设置了一个 fiddle ,它不起作用,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 像素,除以二。

关于css - 固定宽度的中间 div 和它两侧的两个 flex 宽度的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19937321/

25 4 0