垂直水平居中即垂直与水平方向上都要居中,也就是视觉效果中的,处于视图的正中间。下面,咱们来说讲几个css中经常使用的垂直水平居中的解决方案css
一、把外层的div的显示方式设置为table
,即display: table;
html
二、把内层的div的显示方式设置为table-ceil
,即display: table-ceil;
浏览器
这样一来,咱们就能够把这格html结构当作表格和表格中的一个小格。因为表格中只有一个ceil,因此它会自动撑开整个表格,给它设置宽高是无效的,它的宽高是wrapper的宽高。ceil中的内容content就能够自动垂直居中了。app
其中:布局
vertical-align: middle;
text-align: center;
具体代码以下:flex
<div class="wrapper"> <div class="ceil"> <div class="content">Hello world!</div> </div> </div>
css代码:spa
.wrapper { display: table; width: 400px; height: 200px; background-color: red; } .ceil { display: table-cell; vertical-align: middle; background-color: blue; text-align: center; }
效果以下:.net
接着咱们把content中的内容加长看看效果:code
从上面能够看到,wrapper原本应该是红色背景的,可是如今整个ceil撑开了整个表格,因此把wrapper的背景覆盖了,呈现出蓝色。orm
优势:
缺点:
绝对定位法。
一、咱们把须要垂直水平居中的position设置为absolute。
二、设置top为0, left为0,margin为宽高一半的负值。即把盒先一种偏中间的地方,而后再进行微调:
<div class="container"> <div class="content">Hello World!</div> </div>
.container{ position: relative; width: 400px; height: 300px; background-color: red; } .content{ position: absolute; width: 100px; height: 100px; background-color: blue; top: 50%; left: 50%; margin-top: -50px; // 高的一半,视实际状况而定 margin-left: -50px; // 宽的一半,视实际状况而定 }
注意:绝对定位absolute
,是相对于最近非static
的祖先元素进行定位的,因此咱们要在其相对定位的元素上定义display
属性。
一样当文字溢出的时候:
优势:
缺点:
content
会溢出,这时咱们能够设置:overflow:auto;
这时当溢出的时候就会出现滚动条。在方法2的基础上进行改动,把margin负值改成transform
和 translate
.container{ position: relative; width: 400px; height: 300px; background-color: red; } .content{ position: absolute; background-color: blue; top: 50%; left: 50%; transform: translate(-50%, -50%); }
优势,不须要定义宽高,灵活性高缺点:仍要注意截断问题
这个方法使用了 position:absolute,有固定宽度和高度的 div。这个 div 被设置为 top:0; bottom:0;。可是由于它有固定高度,其实并不能和上下都间距为 0,所以 margin:auto; 会使它居中。使用 margin:auto;使块级元素垂直居中是很简单的。
<div class="content"> Content here</div>
.content { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; height: 240px; width: 70%; }
优势:
缺点:
最经常使用的单行文本居中
这个方法只能将单行文本居中。
一、把 line-height
设置为那个对象的 height
值使文本垂直居中
二、把 text-align
设置为center,使文本水平居中
<div id="content">Hello world!</div>
.content { height: 100px; line-height: 100px; text-align: center; }
优势:
缺点:
这个方法在小元素上很是有用,例如使按钮文本或者单行文本居中。
完美居中方案 —— flex布局
.parent{ display : flex; width : 300px; height : 300px; background-color : red; } .child{ width : 100px; height : 50px; margin : auto; background-color: green; }
关键点:
一、display:flex;
二、margin:auto;
参考资料:
css实现垂直居中的5种方法