<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent3{
position: relative;
height:300px;
width: 300px;
background: #FD0C70;
}
.parent3 .child{
position: absolute;
top: 50%;
left: 50%;
color: #fff;
transform: translate(-50%, -50%);
}
</style>
<body>
<div class="parent3">
<div class="child">hello world-3</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent4{
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height:300px;
background: #FD0C70;
}
.parent4 .child{
color:#fff;
}
</style>
<body>
<div class="parent4">
<div class="child">hello world-4</div>
</div>
</body>
</html>
2、
一、假借图片法
这个方法把一些 div 的显示方式设置为inline-block,和图片同样,所以咱们可使用图片的 vertical-align 属性。
<div id="wrapper">
<div id="likeImg">
<div class="content">Content goes here</div>
</div>
</div>
#wrapper {
display: table;
}
#likeImg {
display: inline-block;
vertical-align: center;
}
优势:
在各类浏览器中兼容性都很是好,ie6和7中有间距问题
缺点:
很容易影响其余的布局,致使网页布局所有瘫痪
二、绝对定位法
这个方法使用绝对定位的 div,把它的 top 设置为 50%,margin-top设置为负的 content 高度。这意味着对象必须在 CSS 中指定固定的高度。
由于有固定高度,或许你想给 content 指定 overflow:auto,这样若是 content 太多的话,就会出现滚动条,以避免content 溢出。
<div class="box">
<div id="content"> Content goes here</div>
</div>
#content {
position: absolute;
top: 50%;
height: 240px;
margin-top: -120px; /* 盒子自己高度的一半 */
}
优势:
适用于全部浏览器
不须要嵌套标签
缺点:
没有足够空间时,content 会消失(相似div 在 body 内,当用户缩小浏览器窗口,滚动条不出现的状况)
三、插入空标签 浮动
这种方法,在 content 元素外插入一个 div。设置此 div height:50%; margin-bottom:-contentheight;
content 清除浮动,并显示在中间。
<div id="box">
<div id="content">Content here</div>
<div id="floater">
</div>
#floater {
float: left;
height: 50%;
margin-bottom: -120px;
}
#content {
clear: both;
height: 240px;
position: relative;
}
优势:
适用于全部浏览器
没有足够空间时(例如:窗口缩小) content 不会被截断,滚动条出现
缺点:
惟一我能想到的就是须要额外的空元素了,可能对于某些强迫症患者来讲是不肯意的(这个方法的应用应该也很广)
四、绝对定位
这个方法使用了一个 position:absolute,有固定宽度和高度的 div。这个 div 被设置为 top:0; bottom:0;。可是由于它有固定高度,其实并不能和上下都间距为 0,所以 margin:auto; 会使它居中。使用 margin:auto;使块级元素垂直居中是很简单的。
<div id="box">
<div id="content"> Content here</div>
</div>
#content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
height: 240px;
width: 70%;
}
优势:
简单粗暴,代码简单,其实设计者当初也根本没想到也能这样用,可是聪明的你们硬是凿出了一条简单的路。
缺点:
IE(IE8 beta)中无效
无足够空间时,content 被截断,可是不会有滚动条出现