css如何让块元素水平垂直居中
- 在知道父元素的宽高时,通过设置margin-left,margin-right的方式来使子元素居中
- 使用定位。在知道子元素的宽高时,定位之后通过设置
left:50%,top:50%,
margin-left:-xx px,margin-top:-xx px。
另外一种写法:
left: calc(50% - xx px);
top: calc(50% - xx px);
以下是代码演示:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
.box {
position: absolute;
width: 200px;
height: 200px;
background-color: orange;
position: absolute;
/* left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px; */
/* left: 50% - 100px; 错误写法*/
/* clac() 可以帮助我们去计算表达式的最终结果 */
/* 运算符号前后有空格 */
left: calc(50% - 100px);
top: calc(50% - 100px);
}
.d1{
width: 100px;
height: 100px;
background-color: red;
/* 设置 margin-left 是 自身宽度的2倍 还多100px */
margin-left: calc(100px * 2 + 100px);
}
</style>
</head>
<body>
<div class="box"></div>
<div class="d1"></div>
</body>
</html>
- 使用定位。在知道子元素的宽高时,定位之后通过设置
left:0,top:0,bottom:0,
right:0,margin:0来使子元素居中 - 使用定位,在父元素子元素宽高都未知时,定位之后通过设置left:50%,top:50%,transfrom:translate(-50%,-50%)
需要注意的是:transform:translate中的-50%是子元素的宽度
以下代码演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 500px;
height: 500px;
background-color: aqua;
position: relative;
}
.container{
width: 250px;
height: 250px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="box">
<div class="container">
</div>
</div>
</body>
</html>
效果图: