专注Java教育14年 全国咨询/投诉热线:444-1124-454
星辉LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 一文告诉你CSS中怎么让div垂直居中

一文告诉你CSS中怎么让div垂直居中

更新时间:2022-09-01 10:03:13 来源:星辉 浏览863次

CSS中怎么让div垂直居中?星辉小编来告诉大家。

方法一:

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

HTML & CSS:

 <div class="wrapper">  
     <div class="cell">
         <div class="content">
           <h1>把div显示方式设置为表格</h1>
         </div>
     </div>
 </div> 
 .wrapper {display:table;background: #FC172E;width: 30%;height: 600px;} 
 .cell {
     display:table-cell; 
     vertical-align:middle;
 }

运行效果:

优点:

content 可以动态改变高度(不需在 CSS 中定义)。当 wrapper 里没有足够空间时, content 不会被截断

缺点:

Internet Explorer(甚至 IE8 beta)中无效

方法二:

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

因为有固定高度,或许你想给 content 指定 overflow:auto,这样如果 content 太多的话,就会出现滚动条,以免content 溢出。

HTML & CSS:

 <div class="content">
   对定位的 div,把它的 top 设置为 50%,top margin 设置为负的 content 高度。这意味着对象必须在 CSS 中指定固定的高度。
 </div>
 .content {
     background: #272822;
     position:absolute; 
     top:50%; height:440px;width: 500px; 
     margin-top:-220px; /* 为高度的一半 */
 }

运行效果:

优点:

适用于所有浏览器

不需要嵌套标签

缺点:

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

方法三:

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

HTML:

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

CSS:

 .content {
     position:absolute; 
     top:0; 
     bottom:0; 
     left:0; 
     right:0; 
     margin:auto; 
     height:440px; 
     width:70%; 
     background: #346FCE;
 }

运行效果:

优点:

简单

缺点:

IE(IE8 beta)中无效

无足够空间时,content 被截断,但是不会有滚动条出现

方法四:

这个方法只能将单行文本置中。只需要简单地把 line-height 设置为那个对象的 height 值就可以使文本居中了。

HTML:

 <div id="content"> 
       这个方法只能将单行文本置中。只需要简单地把 line-height 设置为那个对象的 height 值就可以使文本居中了。
 </div> 

CSS:

 #content {
     margin: 50px auto;
     height:300px; 
     line-height:300px;
     background: #EAA527;
 }

运行结果:

优点:

适用于所有浏览器

无足够空间时不会被截断

缺点:

只对文本有效(块级元素无效)

多行时,断词比较糟糕

这个方法在小元素上非常有用,例如使按钮文本或者单行文本居中。

方法五:

这种方法,在 content 元素外插入一个 div。设置此 div height:50%; margin-bottom:-contentheight;。

content 清除浮动,并显示在中间。

HTML:

 <div class="content">
       在 content 元素外插入一个 div。设置此 div height:50%; margin-bottom:-contentheight; content 清除浮动,并显示在中间。
 </div>

CSS:

 .floater {
     float:left; 
     height:50%; 
     position:relative;
     margin-top:-250px;
 }
 .content {
     clear:both; 
     height:500px; 
     background: #67930F;
     position:relative;
 }

运行效果:

优点:

适用于所有浏览器

没有足够空间时(例如:窗口缩小) content 不会被截断,滚动条出现

缺点:

唯一能想到的就是需要额外的空元素

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>