500字范文,内容丰富有趣,生活中的好帮手!
500字范文 > 文本在盒子里垂直居中 css

文本在盒子里垂直居中 css

时间:2024-02-15 04:41:22

相关推荐

文本在盒子里垂直居中 css

1. 已知父级宽高并且文本比较简短

.outline0{width:200px;line-height:200px;text-align:center;background:#ccc;}<div class="outline0"><span>test</span></div>

2.转换元素的类型 vertical-align: middle;

.outline2{display:table;width:200px;height: 200px;background:#ccc;}.center{display:table-cell;text-align:center;vertical-align: middle;}<div class="outline2"><span class="center">test test test,test,test test test test test<span></div>

3.适合知道文本比较固定字段时,还有想定哪定哪

.outline3{width: 200px;height: 200px;background: #ccc;position: relative;}.text3{position: absolute;left: 50%;margin-left: -90px;display: block;width: 180px;top: 50%;margin-top: -21px;text-align: center;}<div class="outline3"><span class="text3">test test test,test,test test test test test<span></div>

4.最好用的

原因:使用top: 50%;left: 50%;, 是以左上角为原点,故不处于中心位置

translate(-50%,-50%) 作用是,往上(x轴),左(y轴)移动自身长宽的 50%,以使其居于中心位置

.outline4{width: 200px;height: 200px;background: #ccc;margin-bottom: 10px;text-align: center;position: relative;}.text4{position: absolute;left: 50%;top: 50%;transform: translate(-50%, -50%);}<div class="outline4"><span class="text4">test test test,test,test test test test test<span></div>

5.flex

.body {display: flex;justify-content: center;align-items: center;height:500px;width:100%;}.box {width: 50px;height: 50px;background:#000;}<div class="body "><div class="box"></div></div>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。