一.浮動float
1.定義
2.特點
- 浮動元素不佔用標準流的位置
- 浮動會影響後面的元素
- 塊級元素和行級元素浮動後會轉換爲行內塊元素
- 多個浮動元素可以在一行上顯示,以浮動元素頂端基線對齊
3. 作用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文字環繞</title>
<style type="text/css">
div {
width: 200px;
border: 1px solid red;
}
img {
width: 100px;
height: 50px;
float: left;
}
</style>
</head>
<body>
<!-- 容器中包含了圖片和文字 -->
<div>
<img src="導航.png">
呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵
呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵
呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵呵
</div>
</body>
</html>
二.清除浮動
1.使用clear:left|right|both
- 在浮動元素最後面添加一個空的塊級或行內塊元素,設置clear:both樣式
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box {
width: 500px;
margin: 0px auto;
background-color: pink;
}
a {
float: left;
height: 50px;
line-height: 50px;
padding: 0px 10px;
text-decoration: none;
}
a:hover {
background-color: gray;
}
</style>
</head>
<body>
<div class="box">
<a href="#">導航1</a>
<a href="#">導航2</a>
<a href="#">導航3</a>
<!-- 使用clear清除浮動的空標籤必須是塊級元素或行內塊元素(行內元素清除無效) -->
<div style="clear:both;"></div>
</div>
</body>
</html>
2.使用overflow:hidden
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.box {
width: 500px;
border: 1px solid green;
overflow: hidden;
}
.div1 {
width: 200px;
height: 300px;
background-color: yellow;
float: left;
}
.div2 {
width: 150px;
height: 200px;
background-color: green;
float: left;
}
</style>
</head>
<body>
<div class="box">
<div class="div1"></div>
<div class="div2"></div>
</div>
</body>
</html>
3.使用僞元素清除 :after
.clearfix:after{
content:"";
display: block;
height: 0px;
line-height: 0px;
clear: both;
visibility: hidden;
}
.clearfix{
zoom:1;
}
4.清除浮動時機(消除父元素後面兄弟元素的錯位影響)
- 父元素沒有設置高度
- 父元素沒有設置高度,則其高度由子元素撐開,但子元素浮動在頁面不佔用位置,所以實際上不佔用高度,對父元素後面的兄弟元素造成錯位影響
- 如果父元素有設置高度,表示父元素已經在頁面佔用了高度,不會對父元素後面的兄弟元素造成錯位影響
- 父元素中所有子元素設置了浮動
- 一組浮動的元素應該放進同一個父容器中進行浮動
- 如果父容器中某個子元素不浮動,會導致子元素錯位
三.overflow
1.概念
2. 屬性值
- visible:默認值,內容不會被修剪,會呈現在邊框之外
- hidden:內容會被修剪,溢出邊框那部分內容會被隱藏
- scroll:內容會被修剪,瀏覽器會顯示滾動條以便查看溢出的內容(無論內容是否溢出,滾動條都會顯示)
- auto:如果內容溢出邊框,則顯示滾動條,如果內容不溢出邊框,則不顯示滾動條
3.overflow:hidden作用
- 解決垂直方向父元素中子元素padding-top導致的塌陷
- 清除浮動,
- 把溢出的內容隱藏
四.樣式初始化
body,p,h1,h2,h3,h4,h5,h6,ul,ol,dl,li,dt,dd {
margin: 0;
padding: 0;
list-style: none;
font-size: 12px;
font-family: "宋體","微軟雅黑";
color: #000;
}
a {
color: #000;
text-decoration: none;
}
a:hover {
color: red;
}
img,input {
margin: 0;
padding: 0;
border: 0 none;
outline-style: none;
}
.clearfix:after {
content: "";
height: 0;
line-height: 0;
display: block;
clear: both;
visibility: hidden;
}
.clearfix {
zoom: 1;
}