我有一个侧边栏 DIV float 在我页面的右侧。侧边栏的 CSS
#sidebar {
position: fixed;
right: 0;
top: 22px;
border: 3px solid #73AD21;
max-width: 300px;
overflow:scroll;
}
我目前正在使用 javascript 函数防止页面主体中的内容与侧边栏重叠
function handleResize() {
var sbw = document.getElementById('sidebar').offsetWidth;
var ww = document.documentElement.clientWidth || document.body.clientWidth;
var bodyWidthVal = 1000;
$("body").css('width', Math.min(bodyWidthVal,(-9 + ww - sbw)));
}
在检测到窗口大小调整或缩放时调用(后者通过鼠标滚轮事件捕获)。神奇的数字“-9”在某种程度上也是必要的,因为在我使用的网络浏览器 (IE 11) 中,sidebar.offsetWidth 似乎没有捕获侧边栏周围边框的宽度
这是有效的,但如果可以用纯 CSS 实现,我宁愿摆脱这个笨拙的解决方案。
最佳答案
有一个更简单的解决方案(实际上有几个)根本不需要 JavaScript。
只需 float 您的内容和侧边栏即可。
使用静态单位只会在特定视口(viewport)上看起来不错。此外,在 CSS 中,宽度和高度属性仅与内容区域的大小有关。填充、边框和边距是单独的大小。可以在 CSS 中通过设置 box-sizing:border-box
来覆盖此默认行为,您希望根据其内容、填充和边框调整大小(仍然不包括边距) .
查看代码中的注释:
/* Change box model default sizing so that padding and borders are
counted into the width of an element */
* { box-sizing:border-box; }
#wrapper {
width:100vw; /* as wide as the viewport */
}
#mainContentArea {
border:1px solid black;
background-color:#e0e0e0;
width:80%;
float:left; /* align element to left of row allowing next element to float up */
height:100vh;
}
#sidebar {
border:1px solid red;
background-color:#808080;
width:20%;
float:left; /* float to left until another floated element is found */
height:100vh;
min-width:100px; /* Don't let the sidebar get smaller than 100px */
}
<div id="wrapper">
<div id="mainContentArea">
</div>
<div id="sidebar">
</div>
</div>
关于javascript - 如何在纯 CSS 中做到这一点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45041460/