css之定位relative及absolute

657 阅读2分钟

relative

relative有如下作用:

  • 限制absolute的定位,也就是relative元素作为absolute元素的参考定位点。
  • 如果子级是定位元素,若想父级的overflow起作用,需要在父级加relative,否则overflow不生效。
  • 无侵入:对于margin-top设置为-50px,那么后面的元素也要往上,布局会变化,如果是relative,那么位置会被占住,后面的元素不会往上过去,这个特性可以用在一些微调上面。
<div class="flex">
  <span class="line"></span>
  <span class="text">文字大小可变.....</span>
  <span class="line"></span>
</div>
.flex {
  display: flex;
  width: 80%;
  margin: 0 auto;
}
.line {
 flex: 1;
 position: relative;
 top: -10px;
 border-bottom: 1px solid #000;
}

css30.jpg

  • 提高层叠上下文,定位元素的层级要高于浮动即普通元素,如果被遮盖了,可以加上relative。
  • relative的top,bottom,left,right是斗争,如果top bottom都存在, 那么top起作用;absolute的top,bottom,left,right是拉伸。

absolute

absolute的特点:

  • 无依赖定位:具体表现是不用top, left来定位,通过margin来显示微调,好处是当布局有调整的时候会自适应,如果用top则把位置定死了,不能自适应。原理是absolute的跟随性,就是原来在什么地方,absolute后仍然在什么地方。所以就能实现无依赖的定位效果。设置绝对定位后,元素脱离文档流,后面的元素会补进来, 也就是后面的元素往前提,形成一个重叠的效果,这是与float的区别,float不会发生重叠。
  • absolute中top, bottom和height同时存在,以height为主。
  • 利用absolute和margin:auto可以实现居中效果
{ 
    position: absolute; 
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    width: 50%; 
    height: 50%; 
    margin: auto; 
}

利用absolute的无依赖定位实现一个导航菜单

需求:在做导航菜单的时候,子级的下拉菜单需要根据子级的文字多少实现自适应,然而父级有relative,导致子级宽度自适应的话是不会超过父级的宽度。

那么,absolute元素如何超出其父级relative元素的宽度?解决方法:父菜单不用relative,子菜单也不用left,right而使用margin定位即可。

<div class="main">
  <div class="father">新闻</div>
  <ul class="child">
    <li>体育新闻</li>
    <li>娱乐与传媒新闻</li>
    <li>健康养生新闻</li>
  </ul>
</div>

.main {
  position: relative;
  width: 50px;
  margin: 40px;
}
.child {
    position: absolute;
}

css31.jpg 当我对父级使用relative的时候,发现子级的宽度也被父级的宽度限制了,不能自适应。所以把父级的relative去掉,子级使用absolute即可

css32.jpg

最后使用margin进行位置的微调:

.child {
  position: absolute;
  margin: 10px 0 0 -10px;
}

css33.jpg