How to make a div be centered vertically and horizontally
code snippet
// HTML
<div class="parent">
<div class="child"></div>
</div>
Absolute positioning
.parent{
position:relative;
}
// 第一种
.child{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
// 第二种(需要固定宽高)
.child{
position:absolute;
width:100px;
height:100px;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-50px;
}
// 第三种(需要固定宽高)
.child{
position:absolute;
width:100px;
height:100px;
left:0;
top:0;
bottom:0;
right:0;
margin:auto;
}
// 第四中(固定宽高 + transform变形)
.child{
position: absolute;
width: 100px;
height: 100px;
left: 50%;
top: 50%;
background: yellow;
transform: translate(-50px, -50px);
}
flex layout
.parent {
width: 500px;
height: 500px;
background: pink;
display: flex;
align-items: center;
justify-content: center;
}
// 子元素可以固定宽高
.parent. child {
width: 100px;
height: 100px;
background: yellow;
}
// 子元素不设置宽高
.parent. child {
background: yellow;
}
table-cell
.parent {
width: 500px;
height: 500px;
display: table-cell;
text-align: center;
vertical-align: middle;
background: pink;
}
.parent .child {
display: inline-table;
/*
// 这种写法也可以
display: inline-block;
display: inline; */
width: 100px;
height: 100px;
background: yellow;
}
Grid
.parent {
width: 500px;
height: 500px;
display: grid;
background: pink;
}
.parent .child {
align-self: center;
justify-self: center;
width: 100px;
height: 100px;
background: yellow;
}
to sum up
There are two situations to center a div vertically and horizontally. The first one is that the element is not fixed in width and height. There are three ways
- Use absolute positioning plus transform offset
- Use flex layout, set align-items: center; justify-content: center;
- Use grid layout, set align-self: center; justify-self: center;
If the element has a fixed width and height, you can use:
- Absolute positioning + transform offset
- Absolute positioning + negative margin value
- Absolute positioning+margin:auto
- Three ways to not fix the width and height
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。