如何让div宽度匹配容器?底部div未居中原因排查
解决底部区块同宽与居中问题
我来帮你搞定这两个问题——让标注的黄色底部区块和红色参考容器同宽,同时解决它不居中的问题。咱们先拆解问题根源,再给出修改方案:
问题原因分析
为什么底部区块不居中?
你给.floating_section加了position:absolute,但它的直接父级.container没有设置position:relative,所以这个绝对定位是相对于外层的.showcase(因为.showcase有position:relative)来定位的,自然没法和红色容器对齐。另外display:inline-block也会干扰它的布局逻辑。为什么没法和红色容器同宽?
.floating_section默认宽度是内容宽度,没有继承.container的width:80%属性,而且定位基准不对,导致它的宽度和容器脱节。
修改方案
只需要调整两处CSS代码就能解决问题:
1. 给红色容器添加定位基准
修改.container的样式,新增position:relative,让内部的绝对定位元素以它为参照:
.container { text-align:center; margin:auto; width:80%; background:red; position: relative; /* 新增:设置定位父级 */ }
2. 调整底部区块的样式
修改.floating_section的样式,去掉多余属性并设置宽度:
.floating_section { position:absolute; bottom:10px; width: 100%; /* 让区块和父容器同宽 */ box-sizing: border-box; /* 防止内边距/外边距撑宽容器 */ /* 去掉display:inline-block,绝对定位元素不需要这个属性 */ background: yellow; /* 可选:加背景色方便查看效果,对应你的黄色圈注 */ }
修改后的完整CSS代码
/*Universal*/ body { margin:0; padding:0; } .container { text-align:center; margin:auto; width:80%; background:red; position: relative; } /*Header*/ header { background-color:rgba(0,0,0,0.3); font-family:'Montserrat',sans-serif; padding:10px; } header ul { margin:0; } header ul li { display:inline; padding:0 10px 0 15px; } header ul li a { color:#353535; font-weight:bold; text-decoration: none; } #main_link { padding-right:50px; } /*Showcase*/ .showcase { height:500px; background-image:url('Showcase.jpg'); background-size:cover; position:relative; } .showcase_overtext { color:#353535; font-family:'Montserrat',sans-serif; font-size:25px; font-weight:bold; position:absolute; top:300px; right:50px; } .showcase_overtext h1, p { margin:5px; } .button { text-align:center; } .floating_section { position:absolute; bottom:10px; width: 100%; box-sizing: border-box; background: yellow; }
这样修改后,黄色底部区块就会和红色容器完全同宽,并且因为定位基准是红色容器,再加上容器本身margin:auto居中,底部区块也会跟着居中啦。
内容的提问来源于stack exchange,提问作者AddB
相关产品推荐
相关产品推荐

