浮动
浮动的特性
1.脱离标准普通流的控制(浮)移动到其他位置(动),俗称脱标
2.浮动的盒子不再保留原来的位置
3.浮动的盒子都在一行内显示,并且顶端对齐排列
注意:浮动的元素是互相贴靠在一起的,如果父级宽度装不下这些盒子,多出的盒子会另起一行对齐
4.浮动元素都会有行内块元素的特性
eg. 如果块级元素没有设置宽度,默认宽度和父级宽度一样宽,但是添加了浮动之后,它的宽度根据内容来定
浮动元素经常和标准流父级搭配使用
网页布局一般采用的策略(网页布局第一准则):
先用标准流的父元素排列上下位置,之后内部子元素采取浮动排列左右位置
eg1
<style>
.box {
width: 1200px;
height: 460px;
background-color: pink;
margin: 0 auto;
}
.left {
float: left;
width: 230px;
height: 460px;
background-color: purple;
}
.right {
float: left;
/* 宽度=父级元素宽度-第一个浮动的元素宽度 */
width: 970px;
height: 460px;
background-color: skyblue;
}
</style>
</head>
<body>
<div class="box">
<div class="left">左侧</div>
<div class="right">右侧</div>
</div>
</body>
eg2 规整布局用ul>li
<style>
/* 清除内外边距 */
* {
margin: 0;
padding: 0;
}
/* 清除标记符号 */
li {
list-style: none;
}
.box {
width: 1226px;
height: 285px;
background-color: pink;
/* 设置外边距,使盒子居中 */
margin: 0 auto;
}
.box li {
width: 296px;
height: 285px;
background-color: purple;
float: left;
/* 设置右外边距 */
margin-right: 14px;
}
/* 这里必须写 .box .last 要注意权重的问题 20 */
.box .last {
/* 最后一个li设置右外边距0 */
margin-right: 0;
}
</style>
</head>
<body>
<ul class="box">
<li>1</li>
<li>2</li>
<li>3</li>
<li class="last">4</li>
</ul>
</body>
eg3
网页布局第二准则:先设置盒子大小,再设置盒子位置
<style>
.box {
width: 1226px;
height: 615px;
background-color: pink;
margin: 0 auto;
}
.left {
float: left;
width: 234px;
height: 615px;
background-color: purple;
}
.right {
float: left;
width: 992px;
height: 615px;
background-color: skyblue;
}
/* 子代选择器(只选择right里的亲儿子) */
.right>div {
float: left;
width: 234px;
height: 300px;
background-color: pink;
/* 左外边距 */
margin-left: 14px;
/* 下外边距 */
margin-bottom: 14px;
}
</style>
</head>
<body>
<div class="box">
<div class="left">左青龙</div>
<div class="right">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>
</div>
</body>