在CSS中有多种方式可以实现div水平垂直居中的效果,以下是常见的几种方式:
- 使用flex布局:
.container { display: flex; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ }
- 使用position和transform属性:
.container { position: relative; } .centered { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
- 使用position和margin属性:
.container { position: relative; } .centered { position: absolute; top: 50%; left: 50%; margin-left: -50%; /* 水平居中 */ margin-top: -50%; /* 垂直居中 */ }
- 使用display: table和display: table-cell:
.container { display: table; width: 100%; height: 100%; } .centered { display: table-cell; text-align: center; /* 水平居中 */ vertical-align: middle; /* 垂直居中 */ }
注意:以上方式中的.container为包裹div的父元素,.centered为要居中的div。可以根据实际需要选择适合的方式。