水平居中和垂直居中

2017-07-24  本文已影响0人  梦边城

假设有如下html结构

<div class="header">
  <div class="item"></div>
</div>

一、实现item在header内水平居中
1、item定宽度

  .header {
    width: 100%;
    height: 60px;
  }
  .item {
    width: 60px;
    margin: 0 auto;
  }

2、item不定宽度
ps: margin-left 回撤多少px需要根据具体情况微调

.header {
  width: 100%;
  height: 60px;
  position: relative;
}
.item {
  position: absolute;
  left: 50%;
  margin-left: -30px;
}

二、item在header内垂直居中
1、

.header {
  width: 100%;
  height: 60px;
  position: relative;
}
.item {
  height: 40px;
  position: absolute;
  top: 50%;
  margin-top: -20px;
}

2、
ps: item设置float后,调节margin-top值就可以实现居中

.header {
  width: 100%;
  height: 60px;
}
.item {
  float: left;
  margin-top: 10px;
}

3、
ps: 利用header的padding属性来实现item居中,要注意的是,header的高要除去padding的值,也就是等于item的高

.header {
  width: 100%;
  height: 40px;
  padding: 10px 0;
}
.item {
  height: 40px;
 }
上一篇 下一篇

猜你喜欢

热点阅读