每日一题 2020-11-20
请列举出css中不定宽高居中(上下左右居中)的方式

方式一
使用 table-cell 来实现不定宽高居中,但是这是很古老的方法了,不推荐这种做法
<!-- HTML -->
<div class="align_box_2">
<span class="align_word">这里显示多行文字。</span>
</div>
/* CSS */
.zxalign_box_2 {
display: table-cell;
width: 550px;
height: 1.14em;
padding: 0 0.1em;
border: 4px solid #beceeb;
color: #069;
font-size: 10em;
vertical-align: middle;
}
.align_box_2 span.align_word {
display: inline-block;
font-size: 0.1em;
vertical-align: middle;
}
方式二
使用 CSS3 新增的 flex(弹性盒子) 实现不定宽高居中,非常推荐,简单易懂,浏览器兼容比较好
<!-- HTML -->
<div class="wrapper">
<div class="inner"></div>
</div>
/* CSS */
.wrapper {
display: flex;
justify-content: center;
align-items: center;
}
.inner {
width: 30px;
height: 30px;
}
方式三
利用 transform 属性 translate 来进行移动
<!-- HTML -->
<div class="wrapper">
<div class="inner"></div>
</div>
/* CSS */
.wrapper {
width: 600px;
height: 800px;
background-color: aqua;
}
.inner {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 30px;
height: 30px;
background-color: #f40;
}
或者使用绝对定位
.wrapper {
position: relative;
width: 600px;
height: 800px;
background-color: aqua;
}
.inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 30px;
height: 30px;
background-color: #f40;
}

浙公网安备 33010602011771号