一. overflow:hidden 溢出隱藏
給一個元素中設(shè)置overflow:hidden,那么該元素的內(nèi)容若超出了給定的寬度和高度屬性,那么超出的部分將會被隱藏,不占位。
/*css樣式*/
<style type="text/css">
div{ width: 150px; height: 60px; background: skyblue;
overflow: hidden; /*溢出隱藏*/
}
</style>
/*html*/
<div style="">
今天天氣很好!<br>今天天氣很好!<br>
今天天氣很好!<br>今天天氣很好!<br>
</div>
效果如下:
![](/d/20211016/6473d5b6dcd64c6486784c7df4687731.gif)
一般情況下,在頁面中,一般溢出后會顯示省略號,比如,當(dāng)一行文本超出固定寬度就隱藏超出的內(nèi)容顯示省略號。
/*只適用于單行文本*/
div{
width: 150px;
background: skyblue;
overflow: hidden; /*溢出隱藏*/
white-space: nowrap; /*規(guī)定文本不進(jìn)行換行*/
text-overflow: ellipsis; /*當(dāng)對象內(nèi)文本溢出時顯示省略標(biāo)記(...)*/
}
效果如下:
![](/d/20211016/f4381b7b10fb2d7512aea6d3f8d29d7f.gif)
二. overflow:hidden 清除浮動
一般而言,父級元素不設(shè)置高度時,高度由隨內(nèi)容增加自適應(yīng)高度。當(dāng)父級元素內(nèi)部的子元素全部都設(shè)置浮動float之后,子元素會脫離標(biāo)準(zhǔn)流,不占位,父級元素檢測不到子元素的高度,父級元素高度為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>
![](/d/20211016/97a3484165b6e70b8357815497ba36b3.gif)
如上,由于父級元素沒有高度,下面的元素會頂上去,造成頁面的塌陷。因此,需要給父級加個overflow:hidden屬性,這樣父級的高度就隨子級容器及子級內(nèi)容的高度而自適應(yīng)。如下:
由于在IE比較低版本的瀏覽器中使用overflow:hidden;是不能達(dá)到這樣的效果,因此需要加上 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>
![](/d/20211016/8debc5f3d74a117417dc75cce35a4e7f.gif)
三. overflow:hidden 解決外邊距塌陷
父級元素內(nèi)部有子元素,如果給子元素添加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>
![](/d/20211016/65e6a7bb16facb753923ac7c05425741.gif)
因此,給父級元素添加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>
![](/d/20211016/4ccaa2a1b0739388fee8aacda810e6de.gif)
到此這篇關(guān)于詳解overflow:hidden的作用(溢出隱藏、清除浮動、解決外邊距塌陷)的文章就介紹到這了,更多相關(guān)overflow:hidden的作用 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持腳本之家!