<分区>
<分区>
我经常使用 line-height 来使行内元素中的文本垂直居中。
我做了这个演示:
body,
section {
width: 100%;
}
section {
background-color: lightGrey;
}
#wrap {
margin: 30px auto;
width: 100%;
max-width: 800px;
text-align: center;
height: 48px;
}
.my-element {
line-height: 48px;
}
<section>
<div id="wrap">
<span class="my-element">My element</span>
</div>
</section>
工作正常。文本在灰色条内完全垂直居中。
但这种方法的问题是:我必须使用父元素的高度并将其固定在那里。
在使用这种模式时是否有更好、更动态的方法。
这样它就不会在父元素的高度发生变化时损坏。
最佳答案
您可以使用 Flexbox 并设置 align-items: center
和 justify-content: center
垂直和水平居中。
section {
background-color: lightGrey;
}
#wrap {
margin: 30px auto;
width: 100%;
max-width: 800px;
text-align: center;
height: 48px;
display: flex;
align-items: center;
justify-content: center;
}
<section>
<div id="wrap">
<span class="my-element">My element</span>
</div>
</section>
关于html - CSS:使用 line-height 进行垂直居中而不给出固定高度。有办法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43305880/