如何用CSS为文本添加上下间距?解决margin-top被覆盖问题
解决浮动元素margin-top被覆盖的问题
针对你遇到的float元素margin-top失效的情况,给你几个实用的解决办法:
清除浮动影响
如果这个div的父容器里还有其他浮动元素,父容器会出现高度塌陷,导致子元素的margin看起来被"吃掉"。可以给父容器加overflow: hidden;,或者用clearfix伪元素清除浮动:.parent-box::after { content: ""; display: table; clear: both; }改用padding替代margin
margin是元素外部间距,容易受其他元素或布局影响;padding是元素内部间距,稳定性更高。把上下margin换成padding:<div id="idTestXxx" style="float:left; margin-left:120px; color:red; font-weight: bold; width: 400px; padding-top:5px; padding-bottom:5px;">※Test display description</div>添加clear属性
如果上方有同方向的浮动元素,当前div的margin-top可能因为浮动元素脱离文档流而不生效。加上clear: both;(或clear:left)强制元素在浮动元素下方排列,margin-top就能正常起作用:<div id="idTestXxx" style="float:left; clear:both; margin-left:120px; color:red; font-weight: bold; width: 400px; margin-top:5px; margin-bottom:5px;">※Test display description</div>替换为现代布局方式
float是旧的布局方案,容易出现各种兼容性问题。如果项目允许,改用flex布局:
给父容器设置display: flex;,去掉div的float属性,此时margin-top/margin-bottom能正常控制间距:<div class="parent-box" style="display:flex;"> <div id="idTestXxx" style="margin-left:120px; color:red; font-weight: bold; width: 400px; margin-top:5px; margin-bottom:5px;">※Test display description</div> </div>
内容的提问来源于stack exchange,提问作者Quiya
相关产品推荐
相关产品推荐

