CSS:Float

CSS 的 Float(浮动),会使元素向左或向右移动,其周围的元素也会重新排列。

Float(浮动),往往是用于图像,但它在布局时一样非常有用。

元素怎样浮动

元素的水平方向浮动,意味着元素只能左右移动而不能上下移动。

一个浮动元素会尽量向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边框为止。

浮动元素之后的元素将围绕它。

浮动元素之前的元素将不会受到影响。如果图像是右浮动,下面的文本流将环绕在它左边:

/*示例*/
<style>
    img
    {
        float:left;
    }
</style>    

彼此相邻的浮动元素

如果你把几个浮动的元素放到一起,如果有空间的话,它们将彼此相邻。

在这里,我们对图片廊使用 float 属性:

<style>
    .thumbnail 
    {
        float:left;
        width:110px;
        height:90px;
        margin:5px;   /*外边距*/
    }
</style>

清除浮动 - 使用 clear

元素浮动之后,周围的元素会重新排列,为了避免这种情况,使用 clear 属性。

clear 属性指定元素两侧不能出现浮动元素。

使用 clear 属性往文本中添加图片廊:

/*固定搭配*/

<style>
    .clearfix {
                *zoom: 1
            }

            .clearfix:before,.clearfix:after {
                content: " ";
                display: block;
                clear: both;
            }
</style>

以上学习笔记整理自菜鸟教程,下面为我的练习code demo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>浮动</title>
    <style>

        div{
            border:1px solid #999;  /* 边框粗细 线条 颜色 */
        }
        #box div{
            width:200px;
            height: 200px;
            background-color: blue;
            color:#fff;
            text-align: center;
            line-height: 200px;
            margin:10px;

            /* 浮动 */
            float:left;  /* left right */
        }

        #box2{
            width:220px;
            height: 220px;
            background-color: red;
            color:#fff;
            text-align: center;
            line-height: 200px;
            margin:10px;
            /*浮动*/
            float:right;
        }

        /* 如何清除浮动 */
        .clearfix {
            *zoom: 1
        }

        .clearfix:before,.clearfix:after {
            content: " ";
            display: block;
            clear: both;
        }

    </style>
</head>
<body>
    <div id="box" class="clearfix">
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
    </div>

</body>
</html>

效果

猜你喜欢

转载自www.cnblogs.com/kumata/p/9484678.html