2012-07-29 74 views
0

請看看這個fiddleinline-block div包裝寬度= 50%,其中包含一些文字

我對於以下兩個類有不同的行爲。

.class2 { 
    width: 49.5%; 
    display: inline-block; 
} 

.class3 { 
    width: 50%; /* Wraps to next line */ 
    display: inline-block; 
} 
  • 我想要做的是平分寬度b/w的兩個div然後開始填寫每個格*有它自己的內容。
  • 但寬度爲50%,如果我在div中放置了一些文本,第二個div將換行到下一行
  • 寬度爲49.x%,它不換行。

爲什麼要包裝?我在一個特殊的div裏工作。

我怎樣才能讓它不包裹並保持寬度= 50%。

除了50%,我不知道如何拿出正確的價值。

回答

1

使用float: left;浮在左邊,你第一次<div>,你也可以在右側使用float: right;浮動你的第二<div>不是使用<div style="clear: both;"></div>來清除浮動元素:

CSS

.class1 { 
    background-color: red; 
    width: 100%; 
} 
.class2 { 
    width: 50%; 
    background-color: blue; 
    color: white; 
    float: left; 
} 

.class3 { 
background-color: green; 
    width: 50%; 
    float: right; 
} 

HTML

<div class="class1"> 
    <div class="class2"> 
     This is demo 
    </div> 
     <div class="class3"> 
      This is demo   
    </div> 
    <div style="clear: both;"> 
</div> 

My fiddle

+0

將你能夠告訴爲什麼浮動解決這個問題?我正在嘗試。 – 2012-07-29 06:14:13

+0

我想這[**文章**](http://designshack.net/articles/css/everything-you-never-knew-about-css-floats/)將幫助你詳細.. – 2012-07-29 06:15:58

+0

非常感謝你很多 – 2012-07-29 06:18:52

1

嘗試浮動你的div像這樣:

.class1 { 
    background-color: red; 
    width: 100%;  
} 
.class2 { 
    width: 50%; 
    display: inline-block; 
    background-color: blue; 
    color: white; 
    float:left;  
} 
.class3 { 
    width: 50%; 
    display: inline-block; 
    background-color: blue; 
    color: white; 
    float:right; 
} 
-1

放一個:

margin:-2px; 

到您的CLASS3。 這不會破壞你的div,但解決你的問題。 不知道爲什麼

0

你不需要求助於float。這是一個相對難看的解決方法,它引入了自己的問題(必須清除浮動元素和/或在包含元素上設置overflow:hidden)。

你不提供你的HTML標記,但我猜你會在元素之間留有空白,就像在Alien先生的回答中一樣。

請參閱Two inline-block, width 50% elements wrap to second line以獲得更好的解決方案。

0

堆棧而不是坐在一起的原因是display:inline-block可以識別空白區域。如果你在第一個div之後有回報,那麼它會選擇並讓它堆疊起來。解決方法將類似於...

<div class="col1"> 

Column one content. 

</div><div class="col2"> 

Column two content. 

</div> 
0

不要使用浮動,它們會導致各種頭痛。就在這個添加到您的CSS:

body,html{ white-space:nowrap; } 
a,pre,p,span,strong,h1,h2,h3,h4,h5,h6{ white-space:normal; } 

...然後確保您網站上的所有文字無論是包含「P」或「範圍」內

0

我經常使用顯示:inline-block的;

但是,顯示:行內塊有一些問題。

我推薦Grids - Pure模式,並寫了一個像Pure的示例代碼。

.class1 { 
    letter-spacing: -0.31em; 
    *letter-spacing: normal; 
    *word-spacing: -0.43em; 
    text-rendering: optimizespeed; 
    font-family: Georgia, Times, "Times New Roman", serif; 
} 

.class2, .class3 { 
    display: inline-block; 
    zoom: 1; 
    letter-spacing: normal; 
    word-spacing: normal; 
    vertical-align: top; 
    text-rendering: auto; 
    font-family: "Hiragino Kaku Gothic ProN",Meiryo,Verdana,sans-serif; 
    width: 50%; 
} 

my fiddle

相關問題