子元素浮动父元素高度为零的解决办法

当一个元素只包含浮动元素的时候,它会出现高度折叠,即元素的上下底边重合,和高度为0效果一样,为了解决这种情况,需要清除浮动。下面是具体的问题和方法。 

一、在最后一个浮动子元素后面添加一个标签div,并且设置style=”clear:both;”,如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../css_com/reset.css">
    <style>
        .parents{
            width: 100%;
            background-color: #4eff5e;
        }
        .son{
            float: left;
            margin:4px;
            width: 300px;
            height: 300px;
            background-color: #ff4236;
        }
    </style>
</head>
<body>
    <div class="parents">
        <div class="son"></div>
        <div class="son"></div>
        <div class="son"></div>
        <div class="son"></div>
        <!--用于处理子元素浮动父元素高度塌陷问题的div-->
        <div style="clear: both"></div>
    </div>
</body>
</html>

二、利用伪元素:after,给ul清除浮动,如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../css_com/reset.css">
    <style>
        .parents{
            width: 100%;
            background-color: #4eff5e;
        }
        .son{
            float: left;
            margin:4px;
            width: 300px;
            height: 300px;
            background-color: #ff4236;
        }
        .parents:after{
            content: "";
            display: block;
            clear: both;
        }
    </style>
</head>
<body>
    <div class="parents">
        <div class="son"></div>
        <div class="son"></div>
        <div class="son"></div>
        <div class="son"></div>
    </div>
</body>
</html>

三、为父元素添加overflow属性,一般情况下属性值设置为hidden,如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="../css_com/reset.css">
    <style>
        .parents{
            width: 100%;
            background-color: #4eff5e;
            overflow: auto;
        }
        .son{
            float: left;
            margin:4px;
            width: 300px;
            height: 300px;
            background-color: #ff4236;
        }
    </style>
</head>
<body>
    <div class="parents">
        <div class="son"></div>
        <div class="son"></div>
        <div class="son"></div>
        <div class="son"></div>
    </div>
</body>
</html>

  

猜你喜欢

转载自www.cnblogs.com/SpringAndMoon/p/12105528.html