如何消除文本元素间的垂直间距且保持居中对齐?
解决两个标题无垂直间距且保持文本居中的问题
问题根源
h1、h2这类标题标签默认带有上下外边距(margin),这就是两个标题之间出现垂直间距的原因。之前用flex布局时没配置正确的居中属性,导致文本失去居中效果。
方法一:直接清除标题默认外边距
直接移除标题的上下外边距,同时保留文本居中样式,最简单直接:
body { background-color: lightblue; } h1, h2 { margin: 0; /* 清除默认上下外边距 */ text-align: center; } h2 { color: navy; font-size: 200px; }
<h1>The Mains Are</h1> <h2>BACK!</h2>
方法二:用Flex容器实现(同时保证居中)
如果想用flex布局,需要给容器设置垂直排列和水平居中属性,同时清除标题外边距:
body { background-color: lightblue; margin: 0; } .title-container { display: flex; flex-direction: column; /* 设置子元素垂直排列 */ align-items: center; /* 让子元素水平居中 */ /* 若需要页面垂直居中,可添加: justify-content: center; min-height: 100vh; */ } h1, h2 { margin: 0; /* 清除默认外边距,消除垂直间距 */ } h2 { color: navy; font-size: 200px; }
<div class="title-container"> <h1>The Mains Are</h1> <h2>BACK!</h2> </div>
注:之前使用flex时文本不居中,是因为默认flex方向为水平排列(
flex-direction: row),且未设置align-items: center来控制水平对齐,调整后即可恢复居中效果。
内容的提问来源于stack exchange,提问作者hello i couldnt think of a goo
相关产品推荐
相关产品推荐

