标签:
在实际应用中,可能有这样的需求,那就是需要div根据内容进行宽度自适应。有很多开发者可能误以为如果不设定div的宽度就可以实现宽度随内容自适应,其实这是错误的,因为在默认状态下,div的宽度值是百分之百,也就是会占满整个父元素宽度。
代码实例如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.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.softwhy.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;
原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=4629
标签:
原文地址:http://www.cnblogs.com/refe/p/5051661.html