如何使用CSS消除Div内文本项之间的间距?
如何用CSS去除div容器中文本项的间距实现无堆叠排列?
我正在编写一个承载多行文本的div容器,需要去除每个文本项之后的间距。当前文本显示效果符合UX/UI提供的XD设计,但文本应无间距堆叠排列,请问是否可以通过CSS实现该需求?
相关代码
CSS
h3 { font-family: BelyDisplay; display: flex; padding: 0px; margin-left: 3rem; margin-right: 3rem; text-align: left; font: normal normal bold 25px/55px Montserrat; letter-spacing: 0px; color: #F0532D; opacity: 1; } h4 { font-family: BelyDisplay; display: flex; padding: 0px; margin-left: 3rem; margin-right: 3rem; align-items: center; text-align: left; letter-spacing: 0px; opacity: 1; font: normal normal bold 18px/22px Montserrat; color: #483735; } .role-text{ font-family: Montserrat-Regular; margin-left: 3rem; margin-right: 3rem; padding-top: 1rem; padding-bottom: 1rem; text-align: left; letter-spacing: 0px; opacity: 1; font: normal normal normal 18px/22px Montserrat; color: #483735; }
HTML
<div class="textbox"> <span id="close" onclick="this.parentNode.remove(); location.reload(); return false;" class="btn btn-default large"> <img src="/src/Esc X.svg" height="33" width="33"></img> </span> <h2>${roleTypes[role]?.title ?? 'none'}</h2> <div id="card-div"> <p class="role-subtitle">${roleTypes[role]?.subtitle ?? 'none'}</p> <h3>CHARGE</h3> <h4>${roleTypes[role]?.chargesubtitle ?? 'none'}</h4> <p class="role-text">${roleTypes[role]?.chargebody ?? 'none'}</p> <h3>SCOPE</h3> <h4>${roleTypes[role]?.scopesubtitle ?? 'none'}</h4> <p class="role-text">${roleTypes[role]?.scopebody ?? 'none'}</p> <h3>FORECASTING</h3> <h4>${roleTypes[role]?.forecastingsubtitle ?? 'none'}</h4> <p class="role-text">${roleTypes[role]?.forecastingbody ?? 'none'}</p> <h3>COMMUNICATION + RESPONSIBILITY</h3> <h4>${roleTypes[role]?.communicationsubtitle ?? 'none'}</h4> <p class="role-text">${roleTypes[role]?.communicationbody ?? 'none'}</p> </div> </div>
解决方案
当然可以用CSS实现,问题出在元素默认内外边距、过大的行高以及自定义的padding上,调整这些属性即可实现无间距堆叠:
- 先重置所有文本元素的默认内外边距,消除浏览器自带的样式影响
- 调整行高至与字体大小匹配或略大,避免多余的行间距
- 移除
.role-text的上下padding,去掉人为添加的间距 - 可选:如果需要区块间保留极小间距,可统一设置子元素的margin
修改后的CSS代码:
/* 重置所有文本元素的默认内外边距 */ h2, h3, h4, p { margin: 0; padding: 0; } h3 { font-family: BelyDisplay; display: flex; margin-left: 3rem; margin-right: 3rem; text-align: left; /* 调整行高至接近字体大小,消除多余垂直空间 */ font: normal normal bold 25px/28px Montserrat; letter-spacing: 0px; color: #F0532D; opacity: 1; } h4 { font-family: BelyDisplay; display: flex; margin-left: 3rem; margin-right: 3rem; align-items: center; text-align: left; letter-spacing: 0px; opacity: 1; font: normal normal bold 18px/20px Montserrat; color: #483735; } .role-text{ font-family: Montserrat-Regular; margin-left: 3rem; margin-right: 3rem; /* 移除上下padding,消除额外间距 */ padding-top: 0; padding-bottom: 0; text-align: left; letter-spacing: 0px; opacity: 1; font: normal normal normal 18px/20px Montserrat; color: #483735; } /* 可选:若需区块间保留极小间距,可添加此规则 */ #card-div > * { margin-bottom: 2px; /* 根据需求调整,设为0即为完全无间距 */ }
这样调整后,所有文本元素会紧密堆叠,完全符合无间距的需求。
内容的提问来源于stack exchange,提问作者JayPee
相关产品推荐
相关产品推荐

