CSS如何实现div宽度根据内容自适应_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:31:52
Original
1653 people have browsed it

CSS如何实现div宽度根据内容自适应:
建议:尽可能的手写代码,可以有效的提高学习效率和深度。
在实际应用中,可能有这样的需求,那就是需要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>
Copy after login

以上代码可以看出,默认状态下,并不能够实现我们想要的效果。
下面对以上代码进行修改如下:

<!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>
Copy after login

以上代码实现我们想要的效果,并且各浏览器兼容性良好,主要是添加如下核心代码:

display:inline-block; *display:inline; *zoom:1;
Copy after login

原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=4629

更多内容可以参阅:http://www.softwhy.com/divcss/

 

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!