默认状态:
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
.parent {
background: pink;
height: 300px;
}
.child {
background: green;
}
<div class="parent">
<div class="child">
this is child
</div>
</div>
默认
如何使子元素水平垂直居中呢?
- 子元素固定宽高的情况
- 利用定位和margin
.parent{
position: relative;
top: 0;
left: 0;
}
.child{
position: absolute;
top: 50%;
left: 50%;
width: 50px;
height: 50px;
margin-top: -25px;
margin-left: -25px;
}
- 利用定位和
transform
.parent {
position: relative;
top: 0;
left: 0;
}
.child {
position: absolute;
top: 50%;
left: 50%;
width: 50px;
height: 50px;
transform: translate(-50%, -50%)
}
- 利用定位和margin
.parent {
position: relative;
top: 0;
left: 0;
}
.child {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
width: 50px;
height: 50px;
}
- 子元素宽高不定
- 利用定位和
transform
.parent {
position: relative;
top: 0;
left: 0;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
}
- 利用flex
.parent{
display: flex;
justify-content: center;
align-items: center;
}
居中
网友评论