css的div垂直居中的方法,百分比div垂直居中

咱们都知道,固定高宽的div在网页中垂直居中很简单,相信你们也很容易的写出来,可是不是固定高宽的div如何垂直居中呢?咱们在网页布局,特别是手机等web端网页常常是不固定高宽的div,那么这些div如何垂直居中呢?这篇文章,我总结一下。css

固定高宽div垂直居中

enter image description here

如上图,固定高宽的很简单,写法以下:html

position: absolute;
 left: 50%;
 top: 50%;
width:200px;
height:100px;
margin-left:-100px;
margin-top:-50px;

不固定高宽div垂直居中的方法

方法一:css3

用一个“ghost”伪元素(看不见的伪元素)和 inline-block / vertical-align 能够搞定居中,很是巧妙。可是这个方法要求待居中的元素是 inline-block,不是一个真正通用的方案。web

html以下:浏览器

 
class="block" style="height: 300px;">
class="centered">

haorooms案例题目

haorooms案例内容,haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容布局

css以下:post

.block {
  text-align: center;
}


.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; 
}

 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 50%;
}

方法二:flex

能够用table布局方法,可是这种方法也有局限性!ui

写法以下:spa

 

style="width: 100%;">

因为table写法比较费时,你也能够用div代替table,写法以下:

html:

 
class="something-semantic">
class="something-else-semantic">  Unknown stuff to be centered.

css:

.something-semantic {
   display: table;
   width: 100%;
}
.something-else-semantic {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

方法三,终极解决方法:

以上2中方法可能都有其局限性,我介绍的第三中方法是比较成熟的不是固定高宽div的垂直居中的方法!可是方法是css3的写法,想兼容IE8的童鞋们,建议用上面的方法!

方法和咱们固定高宽的差很少,可是不用margin咱们用的是 translate()

demo以下:

xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
http-equiv="Content-Type" content="text/html;charset=UTF-8"> haorooms不固定高度div写法 .center {position: fixed; top: 50%; left: 50%; background-color: #000; width:50%; height: 50%; -webkit-transform: translateX(-50%) translateY(-50%); }
class="center">

我上面的css只是针对webkit内核的浏览器,其余内核浏览器写法以下:

-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);

关于每一个浏览器的写法,能够看看我以前的一篇文章:http://www.haorooms.com/post/css_common

有些弹出层的样式,也能够用这个方法居中

position: fixed;
top: 50%;
left: 50%;
width: 50%;
max-width: 630px;
min-width: 320px;
height: auto;
z-index: 2000;
visibility: hidden;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);

css3不定宽高水平垂直居中

只要三句话就能够实现不定宽高水平垂直居中。

justify-content:center;//子元素水平居中
align-items:center;//子元素垂直居中
display:-webkit-flex;

在父级元素上面加上上面3句话,就能够实现子元素水平垂直居中。

style="text-align: center; vertical-align: middle;"> Unknown stuff to be centered.
相关文章
相关标签/搜索