css

css中div水平垂直居中的方式有哪些

小亿
98
2023-08-03 12:32:42
栏目: 编程语言

在CSS中有多种方式可以实现div水平垂直居中的效果,以下是常见的几种方式:

  1. 使用flex布局:
.container {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}
  1. 使用position和transform属性:
.container {
position: relative;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
  1. 使用position和margin属性:
.container {
position: relative;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
margin-left: -50%; /* 水平居中 */
margin-top: -50%; /* 垂直居中 */
}
  1. 使用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。可以根据实际需要选择适合的方式。

0
看了该问题的人还看了