Centered horizontally and vertically
1. Implementation of grid layout
<style>
html,body{
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: grid;
place-content: center;
}
</style>
<body>
<div class="container" style="width: 100px; height: 100px; background: rgb(206, 100, 100)">块状元素</div>
</body>
achieve effect
2. Flex layout implements flex+margin
<style>
html,body{
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: flex;
}
.container{
margin: auto;
}
</style>
<body>
<div class="container" style="width: 100px; height: 100px; background: rgb(206, 100, 100)">块状元素</div>
</body>
The effect is as above
3. Positioning layout
<style>
//子绝父相
html,body{
margin: 0;
padding: 0;
width: 100%;
height: 100%;
position: relative; //相对定位
}
.container{
position: absolute; //绝对定位,相对于祖先元素位置移动,如果没有祖先元素则以浏览器为基准定位
top: 50%;
left: 50%;
transform: translate(-50%, -50%); //将元素向左移动50%的宽度,向上移动50%的宽度
}
</style>
<body>
<div class="container" style="width: 400px; height: 400px; background: rgb(93, 185, 210)">块状元素</div>
<div class="container" style="color: red;">不定宽高的块状元素</div>
<span class="container" style="color: green;">行内元素</span>
</body>
Block-level elements are centered horizontally
Fixed width:
Add margin:0 auto to the block-level element that needs to be centered; (the width of the block element must have)
Align block-level elements vertically
The parent element sets display: flex and align-items: center;
Requirement: the parent element must display and set the height value
3. Block-level elements are centered horizontally and vertically
1. Parent element (fixed height) setting
display:flex;
align-items:center;
Block-level elements (fixed width) set margin: 0 auto;
2. Realize horizontal and vertical centering with variable width and height: (in the test, both the block-level element and the parent element need to set the width and height respectively)
parent element settings
display:flex;
justify-content:center; //The sub-element is centered horizontally
align-items:center; //The sub-element is vertically centered