首页 > 代码库 > css垂直居中:5种方法
css垂直居中:5种方法
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<style>
/*方法四*/
/* This parent can be any width and height */
.block {
height: 300px;
text-align: center;
background: #FFE1CC;
border: 2px solid #91C001;
}
/* The ghost, nudged to maintain perfect centering */
.block:before {
height: 100%;
content: ‘‘;
display: inline-block;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can also be of any width and height */
.centered {
width: 50%;
display: inline-block;
vertical-align: middle;
background: #A3E6F1;
}
</style>
<body>
<!--
垂直居中:方法一
使用:display:table;vertical-align:middle;
-->
<div style="width: 100%; height: 50px; display: table;border: 1px solid #333; background: #E0EAF4;">
<div style="text-align: left; line-height: 50px;">项目质监机构</div>
<div style="display: table-cell; vertical-align: middle;">
<a style="border: 1px solid #333; height:2px; width:10px;"></a>
</div>
</div>
<!--
垂直居中:方法二
使用:position:absolute;写法一
-->
<div style="position: relative; height: 150px; background-color: #C5C5FD;">
<div style="position:absolute; background:#6F66FB; width: 100px; height: 100px; margin: auto; top: 0; bottom: 0; left: 0; right: 0;"></div>
</div>
<!--
垂直居中:方法二
使用:position:absolute;写法二
-->
<div style="position: relative; height:140px; background: #333; border: 5px dashed #658945;">
<div style="position: absolute; height: 50px; width: 50px; top: 50%; margin-top: -25px; background: #84F754; left: 50%; margin-left: -25px;"></div>
</div>
<!--
垂直居中:方法三
使用:display:flex;
justify-content: center;水平居中
align-items: center; 垂直居中
IE9,IE8下不支持;
-->
<div style="display: flex; display: -webkit-flex; height: 200px; background: #FFFFCC; border: 3px solid #C0014E; align-items: center; justify-content: center;">
<div style="height:70px; width:70px; background: #29F9F9;"></div>
</div>
<!--
垂直居中:方法四
使用:display:inline-block;
-->
<div class="block">
<div class="centered">
<h1>haorooms案例题目</h1>
<p>haorooms案例内容,haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容</p>
</div>
</div>
</body>
</html>
css垂直居中:5种方法