下面讲述了子元素在父元素中垂直水平居中的几种方式(不完全)-----定位法、弹性盒法、表格法。
定位法:
1)第一种方式适用于子元素宽高已知的情况
在已知子元素宽高的情况下,
父元素设置relative定位,子元素设置absolute定位向下移动50%,向右移动50%,
子元素外边框margin向左、向上分别移动子元素宽高的一半。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>子元素在父元素中垂直水平居中--定位法(1)</title>
<style type="text/css">
.parent{
width: 200px;
height: 300px;
background-color: skyblue;
position: relative;
}
.child{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
2) 第二种方式适用于子元素宽高未知的情况,相较于第一种方式这种方式较为方便
父元素设置relative定位,子元素设置absolute定位向下移动50%,向右移动50%,
子元素添加transform转换属性,分别向左、向上移动50%。
translate是移动的意思,它有两个值,第一个值表示x轴方向上的移动,第二个值表示y轴方向上的移动。
取正值表示向右和向下移动;取负值表示向左和向上移动。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>子元素在父元素中垂直水平居中--定位法(2)</title>
<style type="text/css">
.parent{
width: 200px;
height: 300px;
background-color: skyblue;
position: relative;
}
.child{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
3)第三种方式同样适用于子元素宽高未知的情况,相较于第一种方式这种方式较为方便
弹性盒法
弹性盒(flexbox),是一种新的布局方式。引入弹性盒布局可以更加有效的排列子元素中的子元素。
display属性的值为flex,可以定义弹性盒布局,
justify-content 设置子元素在父元素中水平对齐方式,
align-items 设置子元素在父元素中垂直对齐方式,
以上三个属性都是设置在父元素上的。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>子元素在父元素中垂直水平居中--弹性盒法</title>
<style type="text/css">
.parent{
width: 200px;
height: 300px;
background-color: green;
display: flex; /*弹性盒布局*/
justify-content: center; /*子元素水平居中对齐*/
align-items: center; /*子元素垂直居中对齐*/
}
.child{
width: 100px;
height: 100px;
background-color: lightgoldenrodyellow;
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>
表格法
一般情况下,display的table-cell属性用的数量较少。
display:table-cell 此元素会作为一个表格单元格显示(类似 <td>和 <th>),设置在父元素上,
vertical-align 设置子元素垂直对齐方式,父元素和子元素上都可以设置,这里是设置在父元素上。
注意:display:table-cell属性也会被浮动、定位等属性影响,应避免同时使用。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>子元素在父元素中垂直水平居中--表格法</title>
<style type="text/css">
.parent{
width: 200px;
height: 300px;
background-color: red;
display: table-cell;/*定义表格元素*/
vertical-align: middle;/*子元素垂直居中对齐*/
}
.child{
width: 100px;
height: 100px;
background-color: orange;
margin: 0 auto;/*水平居中对齐*/
}
</style>
</head>
<body>
<div class="parent">
<div class="child"></div>
</div>
</body>
</html>