Author: battleKing warehouse: Github, CodePen blog: CSDN, nuggets feedback email: [email protected] Special statement: original is not easy, shall not be reproduced without authorization or plagiarism, if need to be reproduced can contact the author authorized
background
We in learning CSS will encounter all sorts of block elements and inline elements center alignment problem, but most of the CSS based tutorials are not system have been carried out to center alignment generalizations, so today I took you to systematically sum up how to use CSS to make block elements and inline elements centered alignment.
Basic architecture
<div class="father"> <div class="children"></div>Copy the code
One, horizontal center
1.1 Block elements within block elements<div>
In the middle
Method 1: Use the padding property of the parent element
.father{
padding:0 30px;
}
Copy the code
Method two: using the margin attribute of the child element
.children{
margin:0 auto;
}
Copy the code
The inline element in the 1.2 block element<text>
In the middle
.father {
text-align: center;
}
Copy the code
Two, vertical center
2.1 Block elements within block elements<div>
In the middle
2.1.1 Use the padding property of the parent element
.father{
padding:30px 0;
}
Copy the code
2.1.2 Use position and transform of child elements to realize vertical centering.
.children{
position:absolute;
top:50%
left:50%
transform: translate(--50%, -50%)}Copy the code
2.1.3 Flex layout implementation using parent elements
.father{
display:flex;
justify-content:center;
align-tiems:center;
}
Copy the code
3.2. Inline elements within block elements<text>
In the middle
3.2.1 Use form elements (Table)
.father{
display:table
}
text{
display:table-ceil;
vertical-align:middle;
}
Copy the code
3.2.2 Use line-height = height of parent element
.father{
width:100%;
height:200px;
line-height:200px;
}
Copy the code
conclusion
- For the block element
A block element
的Horizontal center
, preferentially usemargin:0 auto
- For the block element
Inline elements
的Horizontal center
, preferentially usetext-align: center
- For the block element
A block element
的Vertical center
, preferentially usedisplay:flex
- For the block element
Inline elements
的Vertical center
, preferentially useline-height = height
- Do not use it under any circumstances
display:table
To layout
❤️ thank you
If this article is helpful to you, please support it by clicking a “like”. Your “like” is my motivation for writing.
If you like this article, you can “like” + “favorites” + “forward” to more friends.