如何在两个并排浮动div下方添加水平分隔线hr 优先非浮动布局方案
问题原因
- 你当前需要放在两个浮动区块下方的分隔线
<hr id="hrBelowCustomer">写在了左侧浮动div的内部,只能受左侧父容器范围限制,自然无法覆盖到右侧浮动区块。 - 你给hr写的clear属性写法错误:同一CSS属性重复赋值时,后面的取值会覆盖前面的,因此你写的
clear: left;clear:right实际只有clear:right生效,没有达到同时清除左右浮动的效果。
方案1:修复现有浮动布局的分隔线问题
调整步骤
- 把要放在两个浮动区块下方的hr移出两个浮动div,放在二者的后面
- 修正hr的clear属性为
clear: both,同时清除左右浮动影响
调整后核心代码示例
HTML
<h1 id="quoteSumTitle">Quote Summary</h1> <h4 id="quotePriceText">Total cost "the quote price WIP"</h4> <h5 id="CustomerTitle">Customer</h5> <hr /> <div id="CustomerInfoInline" style="float:left"> <section> <h6>Name: "insert"</h6> <h6>Address: "insert"</h6> <h6>City, State, Zip: "insert"</h6> <h6>SSN: "insert"</h6> <h6>DOB: "insert"</h6> <h6>Email: "insert"</h6> <h6>DOB: "insert"</h6> <h6>Prev. Carrier: "insert"</h6> </section> </div> <div id="CustomerDiscountsInline" style="float:right"> <section> <h6 id="customerBold">Customer Discounts</h6> <h4 id="DiscountsID">discounts will be applied here</h4> </section> </div> <!-- 把hr移到两个浮动div的外面 --> <hr id="hrBelowCustomer" />
CSS
#quoteSumTitle{ text-align:center; margin-bottom: 60px; } #quotePriceText{ text-align:center; margin-bottom:40px; } #CustomerTitle{ color:lightslategray; } #CustomerDiscountsInline{ vertical-align:top; } hr { /* 合并为both同时清除左右浮动 */ clear: both; } #hrBelowCustomer{ /* 浮动布局下top属性对静态定位的hr无效,可删掉这行,根据需要调整margin即可 */ margin-top: 20px; }
方案2:不用浮动的Flex布局实现(更推荐)
Flex布局没有浮动高度塌陷的问题,后续元素不需要额外清除浮动,排版更可控。
调整步骤
- 给两个并排div套一个父容器,设置为
display: flex; justify-content: space-between; align-items: flex-start,即可实现左右两侧顶部对齐、两端分布的效果 - 删掉两个div上的float属性
调整后核心代码示例
HTML
<h1 id="quoteSumTitle">Quote Summary</h1> <h4 id="quotePriceText">Total cost "the quote price WIP"</h4> <h5 id="CustomerTitle">Customer</h5> <hr /> <!-- 新增flex父容器 --> <div class="customer-row"> <div id="CustomerInfoInline"> <section> <h6>Name: "insert"</h6> <h6>Address: "insert"</h6> <h6>City, State, Zip: "insert"</h6> <h6>SSN: "insert"</h6> <h6>DOB: "insert"</h6> <h6>Email: "insert"</h6> <h6>DOB: "insert"</h6> <h6>Prev. Carrier: "insert"</h6> </section> </div> <div id="CustomerDiscountsInline"> <section> <h6 id="customerBold">Customer Discounts</h6> <h4 id="DiscountsID">discounts will be applied here</h4> </section> </div> </div> <hr id="hrBelowCustomer" />
CSS
#quoteSumTitle{ text-align:center; margin-bottom: 60px; } #quotePriceText{ text-align:center; margin-bottom:40px; } #CustomerTitle{ color:lightslategray; } /* 新增flex父容器样式 */ .customer-row { display: flex; justify-content: space-between; align-items: flex-start; } hr { margin-top: 20px; }
内容的提问来源于stack exchange,提问作者Bryce Purnell
相关产品推荐
相关产品推荐

