2012-04-21 37 views
0

我有2個的div,我想垂直位置時,左對齊,我想基於文本的量它們的寬度來包裝。塊元素來包裝上的文本內容

fiddle

<div class="main"> 
    <div class="line">Content content content content</div> 
    <div class="line">Content content</div> 
</div> 

.main { 
    position: absolute; 
    color: white; 
} 
.line { 
    padding: 3px; 
    margin: 2px; 
    background-color: #505050; 
} 

我想出了一個可能的解決辦法,但我想知道是否有比這更直接的解決方案。

我提出的解決方案是讓「.line」顯示:inline-block「,」white-space:nowrap「,並使」.main「」width:0「。

solution fiddle

.main { 
    position: absolute; 
    color: white; 
    width: 0; 
} 
.line { 
    padding: 3px; 
    margin: 2px; 
    background-color: #505050; 
    display: inline-block; 
    white-space: nowrap; 

    /* IE7 fix */ 
    zoom: 1; 
    *display: inline; 
}​ 

是否有這更好的選擇嗎?

爲什麼我問,如果有一個更直接的解決方案的原因是因爲我認爲「寬度:0」和「白色空間:NOWRAP」可能會影響不同的內容。

回答

2

按我理解可能就是你想要的。

.main { 
    color: white; 
} 
.line { 
    padding: 3px; 
    margin: 2px; 
    background-color: #505050; 
    float:left; 
    clear:left; 
} 

入住這http://jsfiddle.net/2kmzK/1/

+0

沒錯,就是它!我不知道你們可以漂浮,清除和元素。順便說一句,那最後沒有「白色空間」。我會在瀏覽器中測試它,然後發佈我的發現。 – jsgroove 2012-04-21 04:18:02

+0

測試它從IE7開始到現代瀏覽器,它的效果很好。漂浮它並同時清理它可以優雅地完成工作。 – jsgroove 2012-04-21 04:27:09

+0

很高興幫助:) – sandeep 2012-04-21 04:40:34