让元素水平垂直居中的四种方法
前言
一、使用 transform 与 position 结合
二、使用 position 定位和 偏移 属性
三、使用 position 定位和 外边距 属性
四、使用 flex 弹性布局
方法一
主要利用transform属性实现上下左右居中
CSS部分
.demo {
100px;
height: 100px;
background-color: greenyellow;
/* 定位须是绝对定位 */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
html部分
<div class="demo"></div>
页面效果展示
方法二 (常用方法)
主要利用absolute属性和偏移属性实现上下左右居中
CSS部分
.demo {
100px;
height: 100px;
background-color: yellowgreen;
/* 定位须是绝对定位 */
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
html部分
<div class="demo"></div>
方法三
主要利用absolute属性和外边距属性实现上下左右居中
CSS部分
.demo {
100px;
height: 100px;
background-color: yellow;
/* 定位须是绝对定位 */
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
html部分
<div class="demo"></div>
方法四
主要利用flex弹性布局
注意:
1、首先将父元素设置为 display:flex;justify-content: center;align-items: center;
2、其次将父元素高度设置为 height:100vh,根据 css3 的规范,1vh 等于视口高度的1%(1vw 等于视口宽度的1%),那么 100vh 就是适口高度的 100%,即占满整个屏幕。
CSS部分
html,body {
margin: 0;
}
.container {
height: 100vh;
/*设置外层盒子display为flex*/
display: flex;
/*设置内层盒子水平居中*/
justify-content: center;
/*设置内层盒子垂直居中*/
align-items: center;
margin: 0 auto;
}
.demo {
100px;
height: 100px;
background-color: green;
}
html部分
<div class="container">
<div class="demo"></div>
</div>