2012-10-19 14 views
0

我需要在一行中顯示字符串「field1 field2 field3」,field1,field2和field3將爲N個字符。使用css在一行中顯示字符串

如何顯示字符串?

<style> 
#div1{ 
    width:1000px; 
    border:1px solid; 
}   
.field1{ 
    display:inline; 
    width:auto; 
} 
.field2{ 
    display:inline; 
    width:auto; 
} 
.field3{ 

    width:auto; 
} 
     </style> 

     <div id="div1"> 
      <div class="field1">Field1(with N number of characters)</div> 
      <div class="field2">Field2(with N number of characters)</div> 
      <div class="field3">Field3(with N number of characters)</div> 
     </div> 
+0

使用跨度而不是divs爲您的字段。這解決了你的問題,沒有任何css的變化 –

+1

禁止顯示field3:內聯他們不在一行? –

+0

您錯過了顯示:.field3中的內聯字段也是寬度:整個div標記爲自動 –

回答

0

我認爲這是想你想

<style> 
#div1{ 
width:auto; 
border:1px solid; 
}   
.field1{ 
display:inline; 
width:auto; 
} 
.field2{ 
display:inline; 
width:auto; 
} 
.field3{ 
display:inline; 
width:auto; 
} 
    </style> 

    <div id="div1"> 
     <div class="field1">Field1(with N number of characters)</div> 
     <div class="field2">Field2(with N number of characters)</div> 
     <div class="field3">Field3(with N number of characters)</div> 
    </div>​ 
+0

Float *和* inline?爲什麼只有一個人就夠了? –

+0

是啊謝謝你顯示錯誤..... –

0

由於Sven指出的那樣,你可以使用跨度。沒有任何css更改,您的所有項目都將顯示爲彼此相鄰。

你的其他選擇是浮動的div,像這樣:

<div id="div1"> 
     <div class="field1 fl">Field1(with N number of characters)</div> 
     <div class="field2 fl">Field2(with N number of characters)</div> 
     <div class="field3 fl">Field3(with N number of characters)</div> 
     <div class="clear"></div><!-- This makes sure you don't float unintended elements in older browsers --> 
    </div> 

,並添加到您的CSS(也刪除您display: inline;規則):

.fl { 
    float: left; 
} 

.clear { 
    clear: both; 
} 

你會想如果field1field2field3的內容是動態的(例如使用javascript替換其他內容的文本),請使用div;但如果你確定你打算把元素裏面的文本,然後使用跨度是好的(例如):

<div id="div1"> 
     <span class="field1">Field1(with N number of characters)</span> 
     <span class="field2">Field2(with N number of characters)</span> 
     <span class="field3">Field3(with N number of characters)</span> 
    </div> 
1

除了打開所有塊級兒童(包括最後div)內聯佈局,您可能需要防止換行。在最簡單的,你可以用這個替換樣式表:

#div1 { 
    white-space: nowrap; 
    border: 1px solid; 
}   
#div1 div { 
    display: inline; 
} 

您可以在元素上設置寬度,如果你有其他的原因這樣做,但上面的代碼工作沒有這樣的設置了。

+0

+1。我不知道所有其他答案都試圖讓這個過程變得更加複雜。 –

0

你不應該爲每個項目需要單獨的類,如果他們都將連續對齊,你可以使用一個類來完成這項工作(除非你要引用特定的類稍後的)。之後:將確保行之後沒有任何內容出現在同一行上。

<style> 
    .field { 
     display: inline-block; 
    } 
    .field:after{ 
     display:block; 
     height: 0; 
     content: ''; 
     clear: both; 
    } 
</style> 

<div id="div1"> 
    <div class="field">Field1(with N number of characters)</div> 
    <div class="field">Field2(with N number of characters)</div> 
    <div class="field">Field3(with N number of characters)</div> 
</div> 
相關問題