如何实现两个h2标题横向并排而非纵向排列?
解决h2文本横向并排(两端对齐)的问题
h2是块级元素,默认会占据整行宽度,因此会呈现纵向排列。要实现你需要的两端对齐效果,可采用以下几种方案:
Flexbox布局(推荐):给父容器添加flex属性,通过
justify-content: space-between实现两端对齐<div style="display: flex; justify-content: space-between;"> <h2>Text</h2> <h2>More Text</h2> </div>inline-block + 自动外边距:将h2转为行内块元素,给第二个元素设置
margin-left: auto<div style="display: flex;"> <h2>Text</h2> <h2 style="margin-left: auto;">More Text</h2> </div>Grid布局:利用网格列布局实现两端对齐
<div style="display: grid; grid-template-columns: auto auto; justify-content: space-between; width: 100%;"> <h2>Text</h2> <h2>More Text</h2> </div>
上述方法均可让两个h2文本横向排列并分别靠向容器两侧,其中Flexbox是兼容性最优、实现最简洁的方案。
内容的提问来源于stack exchange,提问作者rockingheck2
相关产品推荐
相关产品推荐

