练习理解浮动和清除浮动

练习理解浮动和清除★


.css代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>练习理解浮动和清除浮动</title>

    <style>
        /*1.清除浮动左*/
        #div1{
            background:red;
            width:200px;
            height:30px;
            float:left;
        }
        #div2{
            background:green;
            width:200px;
            height:50px;
            float:left;
            clear:left;
        }
        #div3{
            background:blue;
            width:220px;
            height:100px;
        }


        /*2.清除浮动右*/
        #div4{
            background:red;
            width:200px;
            height:30px;
            float:right;
        }
        #div4+div{
            background:green;
            width:200px;
            height:50px;
            float:right;
            clear:right;
        }
        #div6{
            background:blue;
            width:220px;
            height:100px;
            margin-left:auto;
        }


    </style>

</head>
<body>

<p style="font-weight:bold;font-family:楷体">1.清除div2浮动左:左侧不能有浮动,div3用来证明div1和div2确实是浮动的</p>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<p style="font-weight:bold;color:red">如上图,div3高度为100px,因为div1和div2都是浮动的,所以div3向上顶替了div1的位置</p>
<p style="font-weight:bold;color:red">div3在高度上漏出了100-30-50=20px,宽度上漏出了220-200=20px</p>

<p style="font-weight:bold;font-family:楷体">2.清除div5浮动右:右侧不能有浮动,div6用来证明div4和div5确实是浮动的</p>
<div id="div4">div4</div>
<div>div5</div>
<div id="div6">div6</div>
<p style="font-weight:bold;color:red;">如右上图,div6高度为100px,因为div4和div5都是浮动的,所以div6向上顶替了div4的位置</p>
<p style="font-weight:bold;color:red">div6在高度上漏出了100-30-50=20px,宽度上漏出了220-200=20px</p>

</body>
</html>

生成页面效果


知识点总结

  1. 在这个练习中,顺便回顾了层次选择器的知识
#div4+div{
            background:green;
            width:200px;
            height:50px;
            float:right;
            clear:right;
        }

意为选择id为div4的向下同代元素

  1. 学习了一个新的知识:如何让块级元素靠右(存疑)

html代码如下

<div class="parent">
  <div class="block"></div>
</div>

css代码如下

/*方法一 : 将 margin-left 设为 auto 后, 元素左边的 margin 会被尽可能的撑大, 所以自然就把元素挤到右边去了*/
.block{
    margin-left: auto;
}

/*方法二 : 使用 position 定位, 绝对能把元素放到右边去.*/
.parent{
  position: relative;
}
.block{
  position: absolute;
  right: 0;
}

/*方法三 :  使用浮动float*/
.block{
  float: right;
}

/*方法四 : 使用text-align,将块设为行内元素,然后父元素使用 text-align: right; 使块到右边*/
.parent{
  text-align: right;
}
.block{
  display: inline-block;
}

/*方法五 : 使用flex属性,将父元素变为弹性容器, 然后将 justify-content 设为 flex-end, 那么容器中的弹性元素会从右开始排列.*/
.parent{
  display: flex;
  justify-content: flex-end;
}
posted @ 2022-04-25 21:33  无关风月7707  阅读(20)  评论(0编辑  收藏  举报