6

CSS如何实现div宽度根据内容自适应

 1 year ago
source link: https://blog.p2hp.com/archives/9132
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

CSS如何实现div宽度根据内容自适应 | Lenix Blog

小编给大家分享一下CSS如何实现div宽度根据内容自适应 ,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

在实际应用中,可能有这样的需求,那就是需要div根据内容进行宽度自适应。有很多开发者可能误以为如果不设定div的宽度就可以实现宽度随内容自适应,其实这是错误的,因为在默认状态下,div的宽度值是百分之百,也就是会占满整个父元素宽度。
代码实例如下:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="author" content="https://www.yisu.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="https://www.yisu.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宽度根据内容自适应 ”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK