2014-03-13 119 views
0

如果你想在这个的jsfiddle看一看:DIV-宽度减小到其内容的宽度或以上内容的宽度/低于

http://jsfiddle.net/v5GXT/1/

<div class="text"> 
    <div id="image">this is an image with unknown width</div> 
    This is some text above,This is some text above,This is some text above,This is some text above,This is some text above,This is some text above, 
    <div class="code">special content</div> 
    and this is some text below,and this is some text below,and this is some text below,and this is some text below,and this is some text below, 
</div> 

的CSS:

.text{ 
    color:red; 
    text-align:justify; 
    margin-top:20px; 
} 

.code{ 
    border:1px solid blue; 
    border-left:10px solid #ccc; 
    background:#eee; 
    padding:5px; 
    margin:5px; 
} 
.code:before{ 
    display:block; 
    font-size:80%; 
    font-style:italic; 
    content:"Example:"; 
    margin-bottom:5px; 
} 

#image{ 
    float:right; 
    border:2px solid red; 
    height:150px; 
    width:150px; 
    margin-left:40px; 
} 

我希望蓝色的div框(特殊内容)的宽度与上面/下面的文字相同,或者它的内容的宽度,无论哪个更容易。为什么这个div与屏幕一样宽?

任何建议什么是最好的方法?





EDIT1: 简单的解决方案,具有溢出: http://jsfiddle.net/v5GXT/6/

.code{ 
    border:1px solid blue; 
    border-left:10px solid #ccc; 
    background:#eee; 
    padding:5px; 
    margin:5px; 
    overflow-x: hidden; 
} 
+0

附加显示:内联块;到你的.code类 –

+0

你的问题是误导性的,标题说'减少div宽度到内容宽度,但你也提到'div盒的宽度与上面/下面的文字宽度相同。这些完全不同。 –

+0

是的,我改变了 – user3304232

回答

1

我要蓝色的div盒(特殊内容)是相同的宽度 文本高于/低于

你可以添加overflow-x: hidden;.code div元素隐藏水平溢出如下:

.code { 
    border:1px solid blue; 
    border-left:10px solid #ccc; 
    background:#eee; 
    padding:5px; margin:5px; 

    overflow-x: hidden; 
} 

WORKING DEMO

1

这么多不同的方式来做到这一点,这是最简单的人之一:

附上.code在块级div,使.codeinline-block

HTML:

<div class="codeContainer"> 
    <div class="code">special content</div> 
</div> 

CSS:

.codeContainer { 
    display: block; 
} 

.code { 
    display:inline-block; 
    width:auto; 
    border:1px solid blue; 
    border-left:10px solid #ccc; 
    background:#eee; 
    padding:5px; 
    margin:5px; 
} 

DEMO:http://jsfiddle.net/v5GXT/13/

0

检查此fiddle

CSS变化

.code{ 
margin: 5px 190px 0 0; 
}