css-div水平垂直居中

base html
<div class="parent">
<div class="child">child</div>
</div>
base style
* {
margin: 0;
padding: 0;
}
.parent {
border: 1px solid black;
padding: 40px;
}
.child {
border: 1px solid red;
}
不定宽高
方式一:使用定位+transform
.parent {
position: relative;
padding: 40px;
border: 1px solid black;
}
.child {
position: absolute;
left: 50%;
transform: translateY(-50%);
border: 1px solid red;
}
方式二:父元素使用flex布局
display: flex;
justify-content: center;
定宽高
.parent {
position: relative;
border: 1px solid black;
padding: 40px;
}
.child {
width: 100px;
height: 20px;
position: absolute;
left: 50%;
margin-left: -50px;
margin-top: -10px;
border: 1px solid red;
}