CSS 中有多种方法可以实现左右居中,下面介绍几种常用的方法:
/* 方法一:使用 margin 属性 */
.center {
margin: 0 auto;
}
/* 方法二:使用 flexbox */
.parent {
display: flex;
justify-content: center;
}
.child {
/* 不需要设置宽度 */
}
/* 方法三:使用绝对定位和负边距 */
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
/* 方法四:使用网格布局 */
.parent {
display: grid;
justify-content: center;
}
.child {
/* 不需要设置宽度 */
} 以上四种方法均可实现左右居中效果,具体使用取决于具体场景和需求。