CSS(一)清除浮动

问题1:关于清除浮动

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style type="text/css">
		.father{
			background: #ccc;
		}
		.box1,.box2,.box3{
			float: left;
			height: 60px;
			background: red;
			margin: 15px;
		}

	</style>
</head>
<body>
	<div class="father">
		<div class="box1">box1</div>
		<div class="box2">box2</div>
		<div class="box3">box3</div>
		<p class=""></p>
		<p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</p>
	</div>
</body>
</html>

以上是浮动事故发生现场,截图如下:

和box加了margin之后

当我们在style中写个样式p{clear:both;}问题解决。
因此,以后遇到这种情况可以创建一个空的p然后加入样式clear:both解决
这就是关于清楚浮动,总计有三种方法

  • 添加子元素并且写上clear:both
  • 在父元素.father中添加overflow:hidden.
  • 使用after伪对象清除,但是此方法只适用于IE8以上的(下面的代码是方法3)
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        .father{
            background: #ccc;
        }
        .box1,.box2,.box3{
            float: left;
            height: 60px;
            background: red;
            margin: 15px;
        }
        .clear:after{
            content: "";
             0;
            height: 0;
            display: block;
            visibility: hidden;
            clear: both;
        }
    </style>
</head>
<body>
    <div class="father clear">
        <div class="box1">box1</div>
        <div class="box2">box2</div>
        <div class="box3">box3</div>
        <p class=""></p>
        <p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</p>
    </div>
</body>
</html>

问题2:关于脱离文档流

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
	ul{
		list-style: none;
	}
	.nav>li{
		float: left;
	}
	ul a{
		display: block;
		text-decoration: none;
		 100px;
		height: 50px;
		text-align: center;
		line-height: 50px;
		color: white;
		background-color: #2f3e45;
	}
	.nav>li:first-child a{
		border-radius: 10px 0 0 10px;
	}
	.nav>li:last-child a{
		border-radius: 0 10px 10px 0;
	}
	.drop-down{
		position: relative;
	}
	.drop-down-content{
		position: absolute;
		padding: 0;
		display: none;
	}
	h3{
		font-size: 30px;
		clear: both;
	}
	.nav .drop-down:hover .drop-down-content{
		display: block;
	}
	.drop-down-content li:hover a{
		background-color: red;
	}
	</style>
</head>
<body>
	<ul class="nav">
		<li><a href="#">首页</a></li>
		<li class="drop-down"><a href="#">运动</a>
			<ul class="drop-down-content">
				<li><a href="#">排球</a></li>
				<li><a href="#">羽毛球</a></li>
				<li><a href="#">篮球</a></li>
			</ul>
		</li>

		<li><a href="#">什么鬼</a></li>
		<li><a href="#">是什么</a></li>
		<li><a href="#">怎么样</a></li>
	</ul>
	<h3>我是测试文字</h3>
</body>
</html>
原文地址:https://www.cnblogs.com/can-i-do/p/6861987.html