一.子div确定宽高
1.根据子div具体大小设置偏移
宽高大小固定的情况下,设置水平和垂直偏移量为父元素的50%。再根据实际长度将子元素向上和向左挪回一半大小
<head>
<meta charset="utf-8">
<title>子div水平垂直居中</title>
<style>
.father {
background-color: #e6a1dd;
width: 600px;
height: 600px;
position: relative;
}
.child {
background-color: #df0d1f;
width: 200px;
height: 100px;
margin: auto;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -50px;
}
</style>
</head>
<body>
<div class="father">
father
<div class="child">
child
</div>
</div>
</body>
效果图
二.子div不定宽高
1.利用translate
<style>
.father {
background-color: #e6a1dd;
width: 600px;
height: 600px;
position: relative;
}
.child {
background-color: #df0d1f;
margin: auto;
position: absolute;
left: 50%;
top: 50%;
transform: translate(50%, 50%);
-webkit-transform: translateX(-50%) translateY(-50%);
}
</style>
2.使用绝对定位absolute,再设置上下左右偏移为0
<style>
.father {
background-color: #e6a1dd;
width: 600px;
height: 600px;
position: relative;
}
.child {
background-color: #E41627;
width: 100px;
height: 100px;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
</style>
3.使用flex布局父级div设置justify-content:center
和align-items:center
<head>
<meta charset="utf-8">
<title>子div水平垂直居中</title>
<style>
.father {
background-color: #b305ad;
width: 600px;
height: 600px;
display: flex;
justify-content: center;
align-items: center;
}
.child {
background-color: #E41627;
width: 100px;
height: 100px;
}
</style>
</head>