How to realize horizontal and Vertical centering by calculation in CSS
This article mainly explains "how to achieve horizontal and vertical center through calculation". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to center horizontally and vertically through calculation".
1. Son absolute father phase, calculate directly or use calc ()
Add a style:
.box {position: relative;}
.inner {
Position: absolute
/ * Direct calculation * /
/ * top: 150px
Left: 150px; * /
Top: calc (50%-50px); / * use calc () * /
Left: calc (50%-50px)
}
two。 Using margin
The child element sets margin-top;, but there is a problem that parents and children share the outer margin, and the parent element needs to set overflow: hidden;.
Add a style:
.box {overflow: hidden;}
.inner {
Margin: 0 auto
Margin-top: 150px
}
3. Using padding
The parent element sets padding to prevent the parent box from being enlarged. Add box-sizing: border-box;.
Add a style:
.box {
Box-sizing: border-box
Padding: 150px
}
At this point, I believe you have a deeper understanding of "how to achieve horizontal vertical center through calculation". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!