css文字垂直居中|css设置元素垂直居中教程

更新时间:2021-08-17    来源:设计基础    手机版     字体:

【www.bbyears.com--设计基础】

在css使用中设置元素垂直居中也是很受大家喜欢的操作,能为我们的设计带来非常不错的效果。很多人不知道css元素垂直居中怎么设置,下面文章就给大家介绍下css元素垂直居中方法,感兴趣的下面具体来看看。

html代码:

Text here

既然设置子元素的垂直居中,那就要知道父元素的高度,才能知道这所谓的中在哪,对吧?就像你想在一段距离的中间位置站住,那你首先需要知道这段距离有多长,你才能知道中间位置在哪.
注意,我所有的百分比高宽,都是建立在html,body {width: 100%;height: 100%;}这样的设置的基础之上的,如果你没有这样设置,.parent这个div的父元素又是body,body你又没有设置宽高,你就可能看不到效果,.parent这个div的高宽比是相对于它的父元素的,所以你在使用的时候需要确定.parent这个div的父元素设置了宽度和高度的.

(1) 行内文本垂直居中

css代码:

.parent {
    height: 100px;
    border: 1px solid #ccc; /*设置border是为了方便查看效果*/
}
.child {
    line-height: 100px;
}

(2) 行内非文本垂直居中(以img为例)

html代码:

    

css代码

.parent {
    height: 100px;
    border: 1px solid #ccc; /*设置border是为了方便查看效果*/
}
.parent img {
    //注意此时应该保证图片自身的高度或者你设置的高度小于父元素的200px的行高,不然你看不出来居中的效果.
    line-height: 100px;
}

(3) 未知高度的块级元素垂直居中

html代码:

  
    
    sddvsds dfvsdvds
  

第一种方法(不需要加padding):

css代码:

.parent {
  width: 100%;
  height: 100%;
  position: relative;
  /*display: table;*/
}
.child {
  width: 500px;
  border: 1px solid #ccc; /*设置border是为了方便查看效果*/
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

第二种方法(不使用transform):

css代码:

.parent {
    position: relative;
    width: 100%;
    height: 100%;
}
.child {
  width: 500px;
  border: 1px solid #ccc;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 30%;
  margin: auto;
}

第三种方法(需要加padding):

css代码:

#parent {
  padding: 5% 0;
}
#child {
  padding: 10% 0;
}

第四种方法:

(使用display: table,此种方法也适用于行内文本元素的居中):

css代码:

.parent {
  width: 100%;
  height: 100%;
  display: table;
}
.child {
  display: table-cell;
  vertical-align: middle;
}

第五种方法(flex布局,这里需要考虑兼容性奥!)

css 代码:

.parent {
    width: 100%;
    height: 100%; /*这里一定要写高度奥!*/
    display: flex;
    align-items: center;
    justify-content: center;
  }

(4) 已知高度的块级元素垂直居中

html代码:

  
    
    sddvsds dfvsdvds
  

css代码:

#parent {
  height: 300px;
}
#child {
  height: 40px;
  margin-top: 130px; /*这个只为父元素的高度减去这个元素的高度除以二计算得到的*/
  border: 1px solid #ccc;
}

本文来源:http://www.bbyears.com/wangyezhizuo/136489.html

猜你感兴趣

热门标签

更多>>

本类排行