Blog.csdn.net/freshlover/…
Horizontal center
- Inline element: text-align:center;
- Flex layout: display:flex; justify-content:center;
- Common (premise: width value has been set) : margin-left:auto; margin-right:auto; margin:0 auto;
- Neutral block elements: Change the dispaly property of a block element to inline and set the parent to text-Aline: Center. The disadvantage of this approach is that you can no longer set the width or height of the element
<div style="text-align: center;" > <div style="display: inline;" < div style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; white-space: inherit;"Copy the code
Vertical center
- Height: 100px; line-height:100px;
- table-cell:
html
<div class="box box1"> <div class="box box1">Copy the code
css
.box1{
display: table-cell;
vertical-align: middle;
text-align: center;
}
Copy the code
- Flex layout: display: flex; justify-content:center; align-items:center;
Horizontal and vertical center
- Option 1: Position element known width parent element set to: position: relative; The child element is set to: position: Absolute; 50% above, 50% to the left, and then subtract the width of the element itself
html
<div class="box">
<div class="content">
</div>
</div>
Copy the code
css
.box {
background-color: #FF8C00;
width: 300px;
height: 300px;
position: relative;
}
.content {
background-color: #F00;
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin: - 50px 0 0 - 50px;
}
Copy the code
-
Margin: -50px 0 0-50px; margin: -50px 0 0-50px; Transform: translate(-50%,-50%);
-
Scenario 3 Flex layout: display: Flex; justify-content:center; align-items:center;
-
Solution 4 does not know its own height and the height of the parent container, using absolute positioning requires only the following three lines:
css
parentElement{
position:relative;
}
childElement{
position: absolute;
top: 50%;
transform: translateY(- 50%);
}
Copy the code
- If there is only one element in the parent container and the parent element has a height set, you only need to use relative positioning
css
parentElement{
height:xxx;
}
.childElement {
position: relative;
top: 50%;
transform: translateY(- 50%);
}
Copy the code