position 和 overflow 一起使用 的情况

1,295 阅读3分钟

position 与 overflow 的使用介绍

最近在写样式时,使用到了position 和 overflow,出现了几种情况,使我重新加深了两者的使用情况;

首先,我们回顾一下position 和 overflow 的各个属性值代表的意思:

下面是position的属性值

需要说明的relative 是没有脱离文档流的,保留自身其位置;absilute和fixed 是脱离文档流的。 这是position 的基本情况;

下面是overflow 的属性值

这个大家常用,就没有什么要特别提及了;

下面是我要说的两个属性一起出现在项目中会发生的效果;

一般项目中我们写的样式 层级都是比较深的,很有可能上升到18代祖宗;这时候我们对样式的把控就有些懵了。 首先说下,我遇到的情况:我的父层(不知道几个层了)使用了overflow:auto,有固定的高度,内容会被修剪的。子层是不定的可以增加和删除动态操作的,有自定义输入框(有下拉弹框的那种),下拉弹框是要使用到position:absolute ;这时候会出现下拉框被修剪掉,必须滚动才能看到全貌,用户体验不好。需要让下拉框在最上层,不被修剪。这就使我充分接触了这两个属性。

下面有几个例子进行说明:

<div class="grandfather">
        <div class="dad">
            <div class="child"></div>
        </div>
        
      .grandfather {
            width: 400px;
            height: 400px;
            background-color: pink;
            position: relative;
        }

        .dad {
            width: 300px;
            height: 300px;
            background-color: blue;
            overflow: auto;
            position:relative;
        }

        .child {
            width: 200px;
            height: 350px;
            background-color: red;
            position: absolute;
            top: 10px;
            z-index: 55;
        }  

如果.dad 没有position属性就是下面样式

两者比较 说明子层position:absolute 虽然脱离文档流,如果父层 有relative 属性值,它的高度是会被计算到的。

我们可能还需要父层有relative , 子层是absolute还要在最上层并且高度不被计算到。

下面例子就是我要说的:

 <div class="grandfather">
        <div class="dad">
            <div class="aa">
                <div class="hh">
                    <div class="child"></div>

                </div>
            </div>
            .grandfather {
            width: 400px;
            height: 400px;
            background-color: pink;
            position: relative;
        }

        .dad {
            width: 300px;
            height: 300px;
            background-color: blue;
            overflow: auto;

        }

        .child {
            width: 200px;
            height: 350px;
            background-color: red;
            position: absolute;
            top: 10px;
            z-index: 55;
        }

        .hh {
            position: absolute;
            background: #fff;
            height: 10px;
            width: 90%;
            margin-top: 5px;
        }
        .aa {
            height: 200px;
            background: #ccc;
            width: 250px;

        }
            

这里你可以看到几个特殊情况,首先要说明的是.hh 使用position:absolute,如果没有使用left top进行操作,它会在其父层下的位置,不会脱离出去;如果是直系父层有定位,它会默认跑到其内容区的左上角,所以在hh 上又加了一层aa。其次就是child是没有被计算到高度的。这个时候dad overflow;auto 也会充分使用到,依据aa的高度而进行修剪。