一. overflow:hidden 溢出隱藏
給一個元素中設置overflow:hidden,那么該元素的內容若超出了給定的寬度和高度屬性,那么超出的部分將會被隱藏,不占位。
/*css樣式*/
<style type="text/css">
div{ width: 150px; height: 60px; background: skyblue;
overflow: hidden; /*溢出隱藏*/
}
</style>
/*html*/
<div style="">
今天天氣很好!<br>今天天氣很好!<br>
今天天氣很好!<br>今天天氣很好!<br>
</div>
效果如下:

一般情況下,在頁面中,一般溢出后會顯示省略號,比如,當一行文本超出固定寬度就隱藏超出的內容顯示省略號。
/*只適用于單行文本*/
div{
width: 150px;
background: skyblue;
overflow: hidden; /*溢出隱藏*/
white-space: nowrap; /*規定文本不進行換行*/
text-overflow: ellipsis; /*當對象內文本溢出時顯示省略標記(...)*/
}
效果如下:

二. overflow:hidden 清除浮動
一般而言,父級元素不設置高度時,高度由隨內容增加自適應高度。當父級元素內部的子元素全部都設置浮動float之后,子元素會脫離標準流,不占位,父級元素檢測不到子元素的高度,父級元素高度為0。那么問題來了,如下:
/*css樣式*/
<style type="text/css">
.box{ background:skyblue; }
.kid{ width: 100px;height: 100px; float:left;}
.kid1{ background: yellow; }
.kid2{ background: orange; }
.wrap{ width: 300px; height: 150px; background: blue; color: white; }
</style>
/*html*/
<body>
<div class="box">
<div class="kid kid1">子元素1</div>
<div class="kid kid2">子元素2</div>
</div>
<div class="wrap">其他部分</div>
</body>

如上,由于父級元素沒有高度,下面的元素會頂上去,造成頁面的塌陷。因此,需要給父級加個overflow:hidden屬性,這樣父級的高度就隨子級容器及子級內容的高度而自適應。如下:
由于在IE比較低版本的瀏覽器中使用overflow:hidden;是不能達到這樣的效果,因此需要加上 zoom:1;
所以為了讓兼容性更好的話,如果需要使用overflow:hidden來清除浮動,那么最好加上zoom:1;
/*css樣式*/
<style type="text/css">
.box{ background:skyblue;
overflow: hidden; /*清除浮動*/
zoom:1;
}
.kid{ width: 100px;height: 100px; float:left;}
.kid1{ background: yellow; }
.kid2{ background: orange; }
.wrap{ width: 300px; height: 150px; background: blue; color: white; }
</style>
/*html*/
<body>
<div class="box">
<div class="kid kid1">子元素1</div>
<div class="kid kid2">子元素2</div>
</div>
<div class="wrap">其他部分</div>
</body>

三. overflow:hidden 解決外邊距塌陷
父級元素內部有子元素,如果給子元素添加margin-top樣式,那么父級元素也會跟著下來,造成外邊距塌陷,如下:
/*css樣式*/
<style type="text/css">
.box{ background:skyblue;}
.kid{ width: 100px;height: 100px; background: yellow; margin-top: 20px}
</style>
/*html*/
<body>
<div class="box">
<div class="kid">子元素1</div>
</div>
</body>

因此,給父級元素添加overflow:hidden,就可以解決這個問題了。
/*css樣式*/
<style type="text/css">
.box{ background:skyblue;
overflow: hidden; /*解決外邊距塌陷*/
}
.kid{ width: 100px;height: 100px; background: yellow; margin-top: 20px}
</style>
/*html*/
<body>
<div class="box">
<div class="kid">子元素1</div>
</div>
</body>

到此這篇關于詳解overflow:hidden的作用(溢出隱藏、清除浮動、解決外邊距塌陷)的文章就介紹到這了,更多相關overflow:hidden的作用 內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章,希望大家以后多多支持腳本之家!