2014-03-13 113 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; 
}