css元素垂直居中的3种方式
水平居中一般都是通过text-align:center,那么垂直居中呢
一、absolute top
我们可以通过absolute top来设置元素垂直居中,设置top:50%,如果元素有高度还要减去高度的一半
代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BFW NEW PAGE</title>
<style>
* {
padding: 0;
margin: 0;
}
#header {
text-align: center;
position: relative;
color: white;
width: 100vw;
height: 100vh;
background-image: url('http://repo.bfw.wiki/bfwrepo/image/5e0c6ed8b80d9.png');
background-size: cover;
background-position: center center;
}
.overlay {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.4);
z-index: 1;
}
.text {
position: absolute;
left: 0;
top: calc(50% - 16px);
right: 0;
bottom: 0;
z-index: 2;
}
</style>
</head>
<body>
<div id="header">
<div class="overlay"></div>
<div class="text">
<h1>WELCOME</h1>
</div>
</div>
</body>
</html>
二、flex
这一种通过flex布...点击查看剩余70%
网友评论0