天天看点

必须知道的css水平、垂直居中

  在网页制作中,有很多种水平、垂直居中方法,本文就归纳如下几种:

  水平居中

  1.

不建议用了。

  2. text-align:center 在父容器里水平居中 inline 文字,或 inline 元素

  3.margin:0 auto;

  4.用 position 加 translate translate(-50%,-50%) 比较奇特,百分比计算不是以父元素为基准,而是以自己为基准。

  

Hello World

  样式

  #ex3_container{

  width:200px;

  height:200px;

  background-color:yellow;

  position:relative;

  }

  #ex3_content{

  left:50%; top:50%;

  transform:translate(-50%,-50%);

  -webkit-transform:translate(-50%,-50%);

  background-color:gray; color:white; position:absolute;

  这个技巧相当嚣张,适用于没固定大小的内容,min-width,max-height,overflow:scroll等。

  5.绝对定位居中

  父容器元素:position: relative

  .Absolute-Center {

  width: 50%;

  height: 50%;

  overflow: auto;

  margin: auto;

  position: absolute;

  top: 0; left: 0; bottom: 0; right: 0;

  注意:高度必须定义,建议加 overflow: auto,防止内容溢出。

  6.视口居中

  内容元素:position: fixed,z-index: 999,记住父容器元素 position: relative

  .Absolute-Center.is-Fixed {

  position: fixed;

  z-index: 999;

  垂直居中

Content goes here

  .wrapper{display:table;}

  cell{display:table;

  vertical-align:middle;

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

域名转让

固定的高度

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

content goes here

  .content {

  position:absolute;

  top:50%;height:240px;

  margin-top:-120px;/ negative half of the height /

  3.content元素外插入一个div

content here

  .floater{

  float:left;

  height:50%;

  margin-bottom:-120px;

  .content{

  clear:both;

  height:240px;

  4.会计元素垂直居中是很简单的

  top:0;

  bottom:0;

  left:0;

  right:0;

  margin:auto;

  widthZ:70%;

  5.line-height

  height:100px;

  line-height:100px;

继续阅读