垂直居中
方法一
这个方法把div
的显示方式设置为表格,因此我们可以使用表格的 vertical-align
属性。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>垂直居中</title> <style type="text/css"> body{ background:#ccc; } #wrapper { display: table; /*here*/ background:blue; } #container { display: table-cell; /*here*/ vertical-align: middle; /*here*/ background: yellow; height:300px; } </style> </head> <body> <div id="wrapper"> <div id="container"> <p>我要用表格属性垂直居中</p> <p>我要用表格属性垂直居中</p> <p>我要用表格属性垂直居中</p> </div> </div> </body> </html>
实现如图:
能在本身里垂直居中;
优点:
container
可以动态改变高度(不需在 CSS 中定义)。当 wrapper
里没有足够空间时,container
不会被截断
缺点:
Internet Explorer(甚至 IE8 )中无效,许多嵌套标签(其实还好)。
方法二
这个方法使用绝对定位的 div
,top
设置为 50%
, margin-top
设置为负的 content
高度。这意味着对象必须在 CSS 中指定固定的高度。
因为有固定高度,或许你想给 content
指定 overflow:auto
,这样如果 content
太多的话,就会出现滚动条,以免content
溢出。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>垂直居中</title> <style type="text/css"> body{ background: #ccc; } #container { position: absolute; top: 50%; height: 200px; margin-top: -100px; /* negative half of the height */ background: yellow; } </style> </head> <body> <div id="container"> <p>我要用绝对定位垂直居中</p> <p>我要用绝对定位垂直居中</p> <p>我要用绝对定位垂直居中</p> </div> </body> </html>
效果图:
相对于父元素垂直居中;
优点:
- 适用于所有浏览器
- 不需要嵌套标签
缺点:
- 没有足够空间时,
content
会消失(类似div
在body
内,当用户缩小浏览器窗口,滚动条不出现的情况)
方法三
这个方法使用了一个 position:absolute
,有固定宽度和高度的 div
。这个 div
被设置为 top:0; bottom:0;
。但是因为它有固定高度,其实并不能和上下都间距为 0,因此 margin:auto;
会使它居中。使用 margin:auto;
使块级元素垂直居中是很简单的
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>垂直居中</title> <style type="text/css"> body{ background: #ccc; } #container { position: absolute; top: 0; bottom: 0; margin: auto; height: 200px; background: yellow; /* 70%;*/ } </style> </head> <body> <div id="container"> <p>我要用绝对定位垂直居中</p> <p>我要用绝对定位垂直居中</p> <p>我要用绝对定位垂直居中</p> </div> </body> </html>
效果图:
方法四:将单行文本垂直居中
这个方法只能将单行文本置中。只需要简单地把 line-height
设置为那个对象的 height
值就可以使文本居中了。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>垂直居中</title> <style type="text/css"> body{ background: #ccc; } #container { height: 100px; line-height: 100px; background: yellow; /* 70%;*/ } </style> </head> <body> <div id="container"> <p>我要用绝对定位垂直居中</p> </div> </body> </html>
效果图:
水平居中
方法一:行内元素水平居中
只需要把行内元素包裹在一个属性display为block的父层元素中,并且把父层元素添加如下属性即可: