2014-01-17 47 views
2

我是CSS/Javascript的新手,遇到了一些看起來應該很簡單的問題。我有一系列的單選按鈕和相應的文字。我希望這一切都以列表形式出現,但出於某種原因,弄亂一個人的屬性會擾亂(或取代?)另一個人的對齊。CSS - >使用非常基本的CSS佈局時遇到問題

努力實現這一點(靠近按鈕上的文字):

enter image description here

如何在CSS樣式呢?

<form id="form1">​ 
    <input type=​"radio" name=​"choices" class=​"radioButtons" value=​"0" id=​"choice0">​ 
    <div id=​"c0" class=​"choiceText">​text here</div>​ 
    <input type=​"radio" name=​"choices" class=​"radioButtons" value=​"1" id=​"choice1">​ 
    <div id=​"c1" class=​"choiceText">​text here</div>​ 
    <input type=​"radio" name=​"choices" class=​"radioButtons" value=​"2" id=​"choice2">​ 
    <div id=​"c2" class=​"choiceText">​text here</div>​ 
</form>​ 

回答

4

的事情是div元素,默認情況下,有其display CSS屬性設置爲block

引用W3Schools,'塊元素是佔用全部可用寬度的元素,並且在它之前和之後都有一個換行符。您可能會注意到<div><p>的行爲如此。

這裏有幾個選項。您可能希望使用默認情況下display屬性已設置爲inline的元素,如spanlabel。內聯元素只需要佔用儘可能多的寬度,並且不強制換行。

您也可以將您的DIV設置爲display:inline而不是標準display:block。但是,你可能會想要在內容之後打破這條路線;在這種情況下,你可以使用:after選擇標記,添加一個換行符 - 這樣的:

<style> 
    div.choicetext { display:inline; } 
    div.choicetext:after { content:"\A"; white-space:pre; } 
</style> 

<form id="form1">​ 
    <input type=​"radio" name=​"choices" class=​"radioButtons" value=​"0" id=​"choice0">​ 
    <div id=​"c0" class=​"choiceText">​text here</div>​ 
    <input type=​"radio" name=​"choices" class=​"radioButtons" value=​"1" id=​"choice1">​ 
    <div id=​"c1" class=​"choiceText">​text here</div>​ 
    <input type=​"radio" name=​"choices" class=​"radioButtons" value=​"2" id=​"choice2">​ 
    <div id=​"c2" class=​"choiceText">​text here</div>​ 
</form>​ 
+0

你是不是做這個稍微複雜嗎?你正在做的是通過'label'標籤實現的。 – pattmorter

+1

我不這麼認爲,@pattmorter。 OP明確提到他有興趣學習如何通過CSS做到這一點 - 他的問題是'我如何在CSS中設計這種風格?'。建議使用標籤標籤並不能解釋他爲什麼得到這樣的結果;額外的信息旨在向他展示爲什麼會發生。 – OnoSendai

2

很簡單,使用<label>標籤。不需要額外的樣式或任何CSS技巧來使其工作。它只是工作。那就是<label>標籤的創建目的。

這是MDN。 這裏的Fiddle

<form id="form1"> 
    <input type="radio" name="choices" class="radioButtons" value="0" id="choice0"> 
    <label id="c0" class="choiceText">text here</label> 
    <input type="radio" name="choices" class="radioButtons" value="1" id="choice1"> 
    <label id="c1" class="choiceText">text here</label> 
    <input type="radio" name="choices" class="radioButtons" value="2" id="choice2"> 
    <label id="c2" class="choiceText">text here</label> 
</form> 
0

試試這個

<form id="form1"> 
     ​ 
     <div id=​"c0" class=​"choiceText">​ 
     <input type=​"radio" name=​"choices" class=​"radioButtons" value=​"0" id=​"choice0"> 
     ​ text here</div> 
     ​ 
     <div id=​"c1" class=​"choiceText"> 
     <input type=​"radio" name=​"choices" class=​"radioButtons" value=​"1" id=​"choice1"> 
     ​ ​text here</div> 
     ​ 
     <div id=​"c2" class=​"choiceText"> 
     <input type=​"radio" name=​"choices" class=​"radioButtons" value=​"2" id=​"choice2"> 
     ​ ​text here</div> 
     ​ 
    </form>