我有一个包含 2 列(主栏和侧边栏)的响应式布局。侧边栏的宽度是固定的,主列的宽度是响应式的。侧边栏是固定宽度,我不能将主列设置为 100%,侧边栏不会明显下降。有没有办法让javascript根据浏览器大小计算主列的宽度? (考虑到它旁边应该有固定宽度的列)
#main {
background-color: #0F0;
float: left;
height: 400px;
width: 100%;
}
#sidebar {
background-color: #C60;
float: right;
height: 400px;
width: 300px;
}
<div id="main">
</div>
<div id="sidebar">
</div>
最佳答案
这可以使用 CSS 的 calc()
函数实现。
#main {
background-color: #0F0;
float: left;
height: 400px;
width: calc(100% - 300px);
}
#sidebar {
background-color: #C60;
float: right;
height: 400px;
width: 300px;
}
body {
margin: 0;
}
<div id="main">
</div>
<div id="sidebar">
</div>
如果你真的想使用 JavaScript,你需要设置 main
的 width
等于 window
的 width
没有滚动条 (document.body.clientWidth
) 减去 sidebar
的 width
。
此外,doMath()
函数需要在 window
调整大小时执行。
var main = document.getElementById('main');
var sidebar = document.getElementById('sidebar');
function doMath() {
main.style.width = document.body.clientWidth - sidebar.offsetWidth + 'px';
}
doMath();
window.onresize = doMath;
#main {
background-color: #0F0;
float: left;
height: 400px;
width: 100%;
}
#sidebar {
background-color: #C60;
float: right;
height: 400px;
width: 300px;
}
body {
margin: 0;
}
<div id="main">
</div>
<div id="sidebar">
</div>
关于javascript - 使用 JS 在主列上响应宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27751988/