在Web开发过程中,我们常常需要将一个元素居中显示,但是当我们不知道元素具体的宽高时,该怎样进行样式的设置呢?在这种情况下,我们可以使用CSS的一些技巧来实现元素的居中显示。 首先,我们可以使用Fle...
在Web开发过程中,我们常常需要将一个元素居中显示,但是当我们不知道元素具体的宽高时,该怎样进行样式的设置呢?在这种情况下,我们可以使用CSS的一些技巧来实现元素的居中显示。
首先,我们可以使用Flex布局来实现元素的水平和垂直居中。代码如下:
.container {
display: flex;
justify-content: center;
align-items: center;
} .container {
position: relative;
}
<br>
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
} .container {
display: table;
width: 100%;
height: 100%;
}
<br>
.item {
display: table-cell;
vertical-align: middle;
text-align: center;
}