八、overflow:hidden;搭配定位不会被修剪的特殊情况

一、知识点:

1.overflow是指内容溢出元素的框发生的情况;

  属性值:visible 默认值,内容呈现在元素框外;

   hidden 内容裁剪,超出内容不可见;

   scoll 超出部分生成滚动条显示;

   auto  如果内容被修剪,则浏览器会显示滚动条以便查看其余的内容;

   inherit 规定从父元素继承overflow属性的值;

2.相对定位: position:relativel;

  绝对定位: position:absolute;

//定位属性在博客五

二、一般情况,会给元素设置overflow:hidden;用于让元素内容自动撑开元素的高度;

示例:

1. 当没有元素内容且不给元素设置高度时

html lang="en">
<head>
    <meta charset="UTF-8">
    <title>overflow:hidden;搭配定位的失效情况</title>
    <style>
        .father{
	     Width:100px;
            border: 1px solid red;
            overflow: hidden;
        }
    </style>
</head>
<body>
<div class="father"></div>
</body>
</html>

由于没有设置元素的高度,所有这里只会显示1px的border边框线; 

2.但当给这个元素添加上内容(直接添加的文字内容/后代元素包含的内容)时,就会撑开元素;
 
 
<div class="father"> 123456 <span>1111</span> <p>我是子元素</p> <div> 我是子元素 <p>我是子元素</p> </div></div>

三、当设置多个同级元素时,若给某个元素使用overflow:hidden;撑开其父元素和相对定位,给其添加子元素并给子元素使用绝对定位时,子元素超出这个元素的部分普遍情况下会被裁剪;

测试代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>overflow:hidden;搭配定位的失效情况</title>
    <style>
        .father_bother{
            width: 200px;
            height: 150px;
            float: left;
            border: 1px solid red;
        }
        .father{
            width: 200px;
            height: 150px;
            border: 1px solid red;
            float: left;
            overflow: hidden;
            position: relative;
        }
        .child{
            width: 600px;
            height: 400px;
            background-color: blue;
            position: absolute;
            top: 100px;
            left: 0;
        }
    </style>
</head>
<body>
<div class="grandfather">
<div class="father_bother"></div>
<div class="father">
    <div class="child">
        我是子元素
        我是子元素
    
</div>
</div>
<div class="father_bother"></div>
</div>
</body>
</html>

但是,若需要让子元素显示时,存在一种overflow:hidden;的特殊情况;

在上面代码的基础上,修改为给祖辈元素设置相对定位,这个元素只设置overflow:hidden;给子元素设置绝对定位,这时子元素就不会被裁剪:

<style>
    .grandfather{ /*修改部分*/
        position: relative;
    }    
    .father_bother{
        width: 200px;
        height: 150px;
        float: left;
        border: 1px solid red;
    }
    .father{  /*修改部分*/
        width: 200px;
        height: 150px;
        border: 1px solid red;
        float: left;
        overflow: hidden;
    }
    .child{
        width: 600px;
        height: 400px;
        background-color: blue;
        position: absolute;
        top: 100px;
        left: 0;
    }
</style>

这里子元素是它的将祖辈元素作为绝对定位的标准,对其父元素设置超出部分隐藏并不会隐藏掉它;

总结方法:当需要给元素设置overflow:hidden;且想令其子元素超出部分不被隐藏,可以给其子元素设置绝对定位,子元素的祖辈元素设置相对定位来实现;

猜你喜欢

转载自blog.csdn.net/weixin_40976555/article/details/80089385