使用margin
设置div的左右margin为auto,并且需要将div的宽度设置为固定值或最大宽度,这种方法适用于在知道宽度的情况下,比较简单实用。
div {
width: 400px;
margin: 0 auto;
}
使用flexbox
将div的父元素设置为display: flex;,并设置justify-content和align-items为center,这样div就会自动居中。
.container {
display: flex;
justify-content: center;
align-items: center;
}
使用绝对定位(absolute positioning)
将div的父元素相对定位(position: relative),div绝对定位(position: absolute)并设置top和left为50%,然后再通过负margin设置元素的偏移量。这种方法适用于不知道宽度高度的情况下。
.container {
position: relative;
}
.container div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* 其它样式 */
}
使用Grid布局:
将div的父元素设置为display: grid;的方式来实现居中对齐。
.container {
display: grid;
justify-items: center;
align-items: center;
}
垂直+水平垂直
#app {
width: 400px;
height: 400px;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgb(71, 135, 135);
}