CSS实现水平垂直居中

1:设置margin:auto方法

这个方法使用了一个 position:absolute,有固定宽度和高度的 div。这个 div被设置为 top:0; bottom:0;。但是因为它有固定高度,其实并不能和上下都间距为 0,因此 margin:auto; 会使它居中。使用 margin:auto;使块级元素垂直居中是很简单的。

#out{
        width: 200px;
	height: 200px;
	background-color: orange;
	position: relative;
}
#in{
	position: absolute;
	width: 100px;
	height: 100px;
	background-color: green;
	margin: auto;
	top: 0;
        left: 0;
        right: 0;
        bottom: 0;
}

<div id="out">
    <div id="in"></div>
</div>

绝对定位的元素的位置相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于<html>,在这里里面的<div>就是相对于外面已定位的<div>进行定位

优点:

  • 简单

缺点:

  • IE(IE8 beta)中无效
  • 无足够空间时,content 被截断,但是不会有滚动条出现

2:已知内外盒子大小设置margin差值法

#out{
        width: 200px;
	height: 200px;
	background-color: orange;
	position: relative;
}
#in{
	position: absolute;
	width: 100px;
	height: 100px;
	background-color: green;
	margin: 50px 0 0 50px;
}

<div id="out">
    <div id="in"></div>
</div>

设置margin的上和左的偏移量分别为两个盒子大小之差的一半

3.负margin值法

这个方法使用绝对定位的 div,把它的 top 和 left 设置为 50%,top margin 设置为负的 content 高度。这意味着对象必须在 CSS 中指定固定的高度和宽度

#out{
	width: 300px;
	height: 300px;
	background-color: orange;
	position: relative;
}
#in{
	position: absolute;
	width: 100px;
	height: 100px;
	background-color: green;
	top: 50%;
	left: 50%;
	margin-top: -50px;
	margin-left: -50px;
}

优点:

  • 适用于所有浏览器
  • 不需要嵌套标签

缺点:

  • 没有足够空间时,content 会消失(类似div 在 body 内,当用户缩小浏览器窗口,滚动条不出现的情况)

4:使用display: table-cell设置成单元格

这个方法把一些 div 的显示方式设置为表格,因此我们可以使用表格的 vertical-align属性。

#content{
    display: table;
}
#out{
	width: 300px;
	height: 300px;
	background-color: orange;
	display: table-cell;
	vertical-align: middle;
}
#in{
	background-color: green;
}
  • 优点:#in 可以动态改变高度(不需在 CSS 中定义)。当 content 里没有足够空间时, out不会被截断
  • 缺点:在IE中无效,嵌套了过多标签

5:使用flex实现居中

#out{
	width: 300px;
	height: 300px;
	background-color: orange;
	display: -webkit-flex;
        display: flex;
        -webkit-align-items: center;
        align-items: center;
        -webkit-justify-content: center;
        justify-content: center;
}
#in{
	width: 100px;
	height: 100px;
	background-color: green;
}

align-items控制垂直方向的居中,justify-content控制水平方向的居中,这是CSS3的新属性。

以上是本人实验成功的几种方法,如有错误欢迎指正,有好的方法也希望分享

猜你喜欢

转载自blog.csdn.net/qq_40856225/article/details/83032308