CSS

浮动元素垂直居中的方法

2019-10-17  本文已影响0人  西瓜鱼仔

浮动元素垂直居中分父盒子有宽高父盒子没有宽高两种情况。

父盒子有宽高

可以用下面两种方法来实现
方法1:

 #parent {
      width: 600px;
      height: 600px;
      position: relative; /*注意父盒子要相对定位*/
      background-color: pink;
    }

 #child {
      background-color:#6699FF;
      width:200px;
      height:200px;
      position: absolute;
      top: 50%; /*容器的一半*/
      left: 50%; /*容器的一半*/
      margin-top:-100px ; /*子盒子高度的一半*/
      margin-left: -100px; /*子盒子高度的一半*/
    }

方法2:

 #child {
      width: 200px;
      height: 200px;
      background-color: #6699FF;
      margin:auto;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }

HTML:

<div id="parent">
  <div id="child"></div>
</div>

运行代码:


父盒子没有宽高

 #parent {
      position: relative; /*注意父盒子要相对定位*/
      background-color: pink;
    }

 #child{
      width: 200px;
      height: 200px;
      background-color: #6699FF;
      margin:auto;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }

HTML:

<div id="parent">
  <div id="child"></div>
</div>

运行结果:



由于父盒子是没有宽高的, 所以子盒子就相对于页面顶部垂直居中了。

父元素内的所有行内元素水平垂直居中

父元素中组合使用display:table-celltext-alignvertical-align,使父元素内的所有行内元素水平垂直居中,这在子元素不确定宽高和数量时,很实用。
示例:垂直居中一个<img>
<img>的容器设置如下:

#container     
{
    display:table-cell;
    text-align:center;
    vertical-align:middle;
}
上一篇 下一篇

猜你喜欢

热点阅读