在實際應用中,可能有這樣的需求,那就是需要div根據內容進行寬度自適應。有很多開發者可能誤以為如果不設定div的寬度就可以實現寬度隨內容自適應,其實這是錯誤的,因為在默認狀態下,div的寬度值是百分之百,也就是會占滿整個父元素寬度。
代碼實例如下:
復制代碼代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<meta name=”author” content=”http://www.survivalescaperooms.com/” />
<title>軟件開發網</title>
<style type=”text/css”>
.parent{
width:400px;
height:400px;
border:1px solid red;
}
.children{
border:1px solid blue;
height:50px;
}
</style>
</head>
<body>
<div class=”parent”>
<div class=”children”>歡迎來到螞蟻部落,今天陽光不錯!</div>
</div>
</body>
</html>
以上代碼可以看出,默認狀態下,并不能夠實現我們想要的效果。
下面對以上代碼進行修改如下:
復制代碼代碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″>
<meta name=”author” content=”http://www.survivalescaperooms.com/” />
<title>軟件開發網</title>
<style type=”text/css”>
.parent{
width:400px;
height:400px;
border:1px solid red;
}
.children{
border:1px solid blue;
height:50px;
display:inline-block;
*display:inline;
*zoom:1;
}
</style>
</head>
<body>
<div class=”parent”>
<div class=”children”>歡迎來到軟件開發網,今天陽光不錯!</div>
</div>
</body>
</html>
以上代碼實現我們想要的效果,并且各瀏覽器兼容性良好,主要是添加如下核心代碼:
復制代碼代碼如下:
display:inline-block;
*display:inline;
*zoom:1;
當然內聯元素不會存在以上麻煩,因為內聯元素并不能夠設置寬度,只能夠隨著內容自適應寬度。
以上所述給大家介紹了CSS 實現div寬度根據內容自適應 的相關知識,希望對大家有所幫助。
新聞熱點
疑難解答