horizontal and vertical center css-div
- Micro-channel scan code number of public attention: the front end of the front end of a large front-end , the pursuit of more refined reading experience, together to learn ah
- After Follow Send key information , free access to a complete set of front-end systems and learning materials old boy python courses
base html
<div class="parent">
<div class="child">child</div>
</div>
basic style
* {
margin: 0;
padding: 0;
}
.parent {
border: 1px solid black;
padding: 40px;
}
.child {
border: 1px solid red;
}
Variable width and height
Method 1: using a positioning + transform
.parent {
position: relative;
padding: 40px;
border: 1px solid black;
}
.child {
position: absolute;
left: 50%;
transform: translateY(-50%);
border: 1px solid red;
}
Second way: the layout of the parent element using flex
display: flex;
justify-content: center;
Fixed width and height
.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;
}