position:relative和position:absolute的差别及使用方法

这几天在做项目时遇到做选项卡的功能时,标题和内容区域的背景颜色不同。且须要选到当前标题时,此标题以下会出现下边框及小三角边框,这样就会超出标题背景颜色需覆盖以下内容区域。这时就须要用到potition:absolute属性。

例如以下图所看到的的效果:



DOM结构:

<div class="active">
        <div class="active_t">
          <ul id="active_list" class="active_list clearfix">
            <li class="activeCur">
              <h2>活动一</h2>
              <h4>10月30日~11月20日</h4>
            </li>
            <li>
              <h2>活动一</h2>
              <h4>10月30日~11月20日</h4>
            </li>
          </ul>
        </div>
      </div>


<!--内容区域 -->

<div class="active_c">
        <div class="active_c_c">

                //这里是内容区域的内容

</div>

</div>


样式例如以下:

.active {
  height: 79px;
  border-bottom: solid 1px #e3ecef;
  position: relative;
  z-index: 0;
  width: 1110px;
  margin: 0 auto;
  padding: 0 0 0 60px;
}
.active .active_t {
  position: absolute;
  margin: 0px auto;
}
.active .active_t ul.active_list {
  padding-top: 15px;
  margin-left: -78px;
}
.active .active_t ul.active_list li {
  float: left;
  color: #ccc;
  margin-left: 78px;
  height: 71px;
  cursor: pointer;
}
.active .active_t ul.active_list li h2 {
  font-size: 28px;
  line-height: 40px;
  font-weight: normal;
}
.active .active_t ul.active_list li h4 {
  font-size: 14px;
  line-height: 24px;
  font-weight: normal;
}
.active .active_t ul.active_list li.activeCur {
  position: relative;
  z-index: 999;
  color: #00addc;
  background: url("../images/active_list.png") no-repeat 0px 63px;
}
.active_c {
  background: #eaf4f6;
  overflow: hidden;
  clear: both;
}
.active_c .active_c_c {
  width: 1080px;
  padding: 35px 45px;
  margin: 0px auto;
  overflow: hidden;
}


总结一下:

这里最外的active的背景颜色为白色,能够设置最外层的宽度为1170而无论背景颜色(假设是其他的背景颜色,那可能就要在外面再设置一个层不固定宽度,)

事实上就是设置active的position:relative,这个是不固定宽度的有白色背景颜色的div,而active_t这个是有1170宽度的内层。再设置里面的li的高度为71px,整体的active的高度为79px,下边的带下边框及小三角的度度为8px。ul上面有15px的padding-top,本来79-15=64px,可是下边框加上小三角的高度为7px,所以64+7=71,即li高度为71px.

posted on 2017-06-17 09:15  yjbjingcha  阅读(266)  评论(0编辑  收藏  举报

导航