[盒子模型:margin/padding+行内块元素对齐+定位+弹性布局]
水平居中:
- 给父元素添加padding左右
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>1.水平居中</title>
<style>
*{
padding: 0;
margin: 0;
}
.father{
width: 200px;/*原来width:500px*/
height: 200px;/*原来height:500px*/
background: green;
padding:0 150px;/*父元素宽度500px padding左右=(父宽-子宽)/2*/
margin: auto;/*父元素居中*/
}
.son{
width: 200px;
height: 200px;
background: pink;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码
- 给子元素添加margin:auto
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2.水平居中</title>
<style>
*{
padding: 0;
margin: 0;
}
.father{
width: 500px;
height: 500px;
background: #000;
margin: auto;
}
.son{
width: 200px;
height: 200px;
background: red;
margin: auto;/*子元素在父元素中居中*/
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码
- 给父元素加text-align:center;子元素加dispaly:inline-block
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>3.水平居中</title>
<style>
*{
padding: 0;
margin: 0;
}
.father{
width: 500px;
height: 500px;
background: #000;
text-align: center;
}
.son{
width: 200px;
height: 200px;
background: green;
display: inline-block;/*行内块元素水平对齐可以用文本对齐控制*/
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码
4.给父元素加position:relative;给子元素加position:absolute;left:50%;margin-left:-子元素的宽度/2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>4.水平居中</title>
<style>
*{
padding: 0;
margin: 0;
}
.father{
width: 500px;
height: 500px;
background: #000;
margin: auto;
position: relative;
}
.son{
width: 200px;
height: 200px;
background: yellow;
position: absolute;
left: 50%;
margin-left: -100px;/*想要子元素在父元素居中,margin-left要是子元素宽度的负一半*/
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码
5.给父元素加position:relative;给子元素加position:absolute;left:50%;transform:translateX(-宽度/2),transform:translateX(-宽度/2)这个属性可以没有宽高,就可以计算出宽高,transform这个属性有的时候不太兼容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>5.水平居中</title>
<style>
.father{
width: 500px;
height: 500px;
background: pink;
position: relative;
}
.son{
width: 200px;
height: 200px;
background: yellow;
position: absolute;
left: 50%;
transform: translateX(-100px);/*让子元素在父元素居中,子元素X轴为子元素宽度的负的一半*/
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码
6.弹性布局,给父元素加display:flex;justify-content:center
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>6.水平居中</title>
<style>
/*弹性布局*/
*{
padding: 0;
margin: 0;
}
.father{
width: 500px;
height: 500px;
background: #000;
margin: auto;
display: flex;
justify-content: center;/*水平居中*/
}
.son{
width: 200px;
height: 200px;
background: paleturquoise;
}
</style>
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
复制代码