首先设置div节点,以及节点的默认样式
<style>
div {
width: 200px;
height: 200px;
background: red;
}
</style>
<body>
<div>
</div>
</body>
代码演示
- 利用transform
div{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% ,-50%);
}
- 利用margin负值
div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
- 利用定位
div{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
- flex布局
body{
width: 800px;
height: 800px;
display: flex;
align-items: center;
justify-content: center;
}
- table
body{
width: 800px;
height: 800px;
display: table-cell;
vertical-align: middle;
}
div{
margin: auto;
}
- 计算属性
body {
width: 800px;
height: 800px;
position: relative;
}
div {
position: absolute;
left: calc((800px - 200px)/2);
top: calc((800px - 200px)/2);
}
总结
前面三种直接设置元素的定位即可,后面三种需要父元素有一定的宽高值