子div(box-container)溢出父div(viewBlocks)的问题求助
解决box-container溢出viewBlocks的问题
问题根源
.box设置了position: absolute,默认会相对于最近的非static定位祖先元素定位。你给.viewBlocks加position: relative只是改变了它的定位参考点,但.box的宽度(250px)远大于.viewBlocks的宽度(190px),所以必然溢出。另外,绝对定位元素会脱离文档流,父元素无法感知它的尺寸,单纯加position: relative不会自动限制子元素尺寸或处理溢出。
方案1:让.box适配viewBlocks的宽度
如果希望.box完全在.viewBlocks内部显示,修改.box的尺寸并利用.viewBlocks的相对定位约束它:
.viewBlocks { text-align: center; float: right; height: 700px; width: 190px; border: 1px solid black; background-color: darkgray; position: relative; /* 保留相对定位,作为.box的定位参考 */ } .box { position: absolute; width: calc(100% - 2px); /* 减去边框宽度,刚好填满容器 */ max-width: 190px; height: 250px; background-color: #f1f1f1; border: 1px solid #d3d3d3; border-radius: 5px; resize: both; overflow: auto; z-index: 1; text-align: center; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; left: 0; /* 固定在容器左侧 */ top: 0; /* 固定在容器顶部 */ }
方案2:让viewBlocks滚动显示溢出内容
如果要保留.box的250px宽度,同时让.viewBlocks能通过滚动查看全部内容,需要去掉.box的绝对定位(让它回到文档流),再给.viewBlocks添加溢出处理:
.viewBlocks { text-align: center; float: right; height: 700px; width: 190px; border: 1px solid black; background-color: darkgray; overflow: auto; /* 开启滚动,显示溢出内容 */ } .box { /* 移除position: absolute,让元素回到文档流 */ width: 250px; height: 250px; background-color: #f1f1f1; border: 1px solid #d3d3d3; border-radius: 5px; resize: both; overflow: auto; z-index: 1; text-align: center; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0 auto; /* 保持内容居中 */ }
方案3:让box-container作为.box的定位容器
如果必须保留.box的绝对定位,可给#box-container设置相对定位,再让.viewBlocks处理#box-container的溢出:
.viewBlocks { text-align: center; float: right; height: 700px; width: 190px; border: 1px solid black; background-color: darkgray; overflow: auto; /* 处理box-container的溢出 */ } #box-container { position: relative; /* 让.box相对于它定位 */ min-height: 250px; /* 确保容器高度至少能容纳.box */ } .box { position: absolute; width: 250px; height: 250px; background-color: #f1f1f1; border: 1px solid #d3d3d3; border-radius: 5px; resize: both; overflow: auto; z-index: 1; text-align: center; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
内容的提问来源于stack exchange,提问作者user18353868
相关产品推荐
相关产品推荐

