2017-03-08 54 views
0

我使用下面的代碼來創建兩個div,一個大的灰色,另一個也有右邊的圖像。代碼工作正常,但兩個div不延伸到圖像結束的地方......我該如何解決這個問題?CSS div擴展到適合圖像

<style> 
div.div1 { 
background-color: #F1F1F1; 
border: 1px solid #CCCCCC; 
padding: 10px; 
} 
div.div2 { 
background-color: #e2d8ba; 
border: 1px solid #000000; 
padding: 10px; 
text-align: justify; 
} 
</style> 
<div class="div1"> 
<div class="div2"> 
<img src="http://www.dailyrecoverymeditations.com/forums/image.php?u=2057&dateline=1404850818" style="float:right; padding-left: 10px;"> 
Testing Text Testing Text Testing Text Testing Text Testing Text Testing Text Testing Text Testing</div> 
</div> 

回答

1

由於圖像是一個浮動的元素,添加overflow: auto;雙方的DIV:

div.div1 { 
 
    background-color: #F1F1F1; 
 
    border: 1px solid #CCCCCC; 
 
    padding: 10px; 
 
    overflow: auto; 
 
} 
 

 
div.div2 { 
 
    background-color: #e2d8ba; 
 
    border: 1px solid #000000; 
 
    padding: 10px; 
 
    text-align: justify; 
 
    overflow: auto; 
 
}
<div class="div1"> 
 
    <div class="div2"> 
 
    <img src="http://www.dailyrecoverymeditations.com/forums/image.php?u=2057&dateline=1404850818" style="float:right; padding-left: 10px;"> Testing Text Testing Text Testing Text Testing Text Testing Text Testing Text Testing Text Testing</div> 
 
</div>

0

當你float一個元素,你remove it from the normal flow of the document。如果您希望父級擴展以適應浮動元素的高度,則需要實現「清除」以清除浮動元素。你可以閱讀所有關於花車在這裏 - https://css-tricks.com/all-about-floats/

有用於清除浮動的許多技術,所以我加了一個作爲.clearfix類,您可以與孩子抹灰任何父母使用。

<style> 
 
    .clearfix:after { 
 
    content: ""; 
 
    display: table; 
 
    clear: both; 
 
    } 
 
    div.div1 { 
 
    background-color: #F1F1F1; 
 
    border: 1px solid #CCCCCC; 
 
    padding: 10px; 
 
    } 
 
    div.div2 { 
 
    background-color: #e2d8ba; 
 
    border: 1px solid #000000; 
 
    padding: 10px; 
 
    text-align: justify; 
 
    } 
 
</style> 
 
<div class="div1"> 
 
    <div class="div2 clearfix"> 
 
    <img src="http://www.dailyrecoverymeditations.com/forums/image.php?u=2057&dateline=1404850818" style="float:right; padding-left: 10px;"> Testing Text Testing Text Testing Text Testing Text Testing Text Testing Text Testing Text Testing</div> 
 
</div>

0
/*CSS*/ 
div.div2 { 
    overflow: auto; 
} 

/*OR*/ 
div.div2 { 
    display: inline-block; 
    width: 100%; 
} 
0

在衆多的選擇,一種是使用屬性display: table

至於問題:

的div不延伸到其中圖像結束

與父元件給定一個顯示table,這將呈現爲根據孩子的比例尺

樣品下面的代碼片段:

div { 
 
    padding: 10px; 
 
    display: table; 
 
} 
 

 
div.div1 { 
 
    background-color: #F1F1F1; 
 
    border: 1px solid #CCCCCC; 
 
} 
 

 
div.div2 { 
 
    background-color: #e2d8ba; 
 
    border: 1px solid #000000; 
 
    text-align: justify; 
 
} 
 

 
div.div2>img { 
 
    float: right; 
 
    padding-left: 10px; 
 
}
<div class="div1"> 
 
    <div class="div2"> 
 
    <img src="http://www.dailyrecoverymeditations.com/forums/image.php?u=2057&dateline=1404850818"> Testing Text Testing Text Testing Text Testing Text Testing Text Testing Text Testing Text Testing</div> 
 
</div>