2013-07-26 33 views
0

我試圖讓第二個文本框與第一個文本框相對。正確的是在右下方。CSS將輸入(文本框)彼此對齊

<!doctype html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <title>Untitled Document</title> 
    </head> 
    <body> 
     <div> 
     <h2>Top</h2> 
     <div> 
      <h2>TextBox 1</h2> 
      <div> 
       <input type="text" /> 
      </div> 
     </div> 
     <div style="float:right;"> 
      <h2>textbox2</h2> 
      <div> 
       <input type="text" /> 
      </div> 
     </div> 
     </div> 
    </body> 
</html> 

回答

2

一種方式是添加float: left;到第一div容器,因爲這縮小其寬度在其內容的寬度,從而允許輸入並排顯示。

http://jsfiddle.net/uwFyp/

+1

不要忘記添加一個「clearfix」級,並將其應用於包裝父div,以便樣式將按預期應用。 .clearfix:在{ 內容:「」;/*舊版瀏覽器不支持空白內容*/ 知名度:隱藏; display:block; 身高:0; 明確:均; } – KnowHowSolutions

0

你基本上只需要浮動兩者都含有你的H2和input元素的div的。您可以漂浮都離開或浮動的第一個左側和右側第二(比如從你上面的代碼本示例):

<!doctype html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <title>Untitled Document</title> 
    </head> 
    <body> 
     <div> 
      <h2>Top</h2> 
      <div style="float:left;"> 
       <h2>TextBox 1</h2> 
       <div> 
        <input type="text" /> 
       </div> 
      </div> 
      <div style="float:right;"> 
       <h2>textbox2</h2> 
       <div> 
        <input type="text" /> 
       </div> 
      </div> 
     </div> 
    </body> 
</html> 

浮動兩個div的離開後,第一個將定位第二個div權。

您可能還會發現需要在第二個浮動div之後立即放置清除div <div style="clear:both;"></div>。這將阻止這兩個元素緊跟在最後一個浮動元素之後。

0

用於輸入對準浮動的div得到棘手凌亂,有很多額外的代碼嘗試,可以通過CSS設置樣式這種更簡潔的方法:

<!doctype html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <title>Untitled Document</title> 
    </head> 
    <style> 
     .horz-inputs label, .horz-inputs input {display: inline-block;} 
     /*add any css you want to the inputs and labels from this point forward 
    </style> 
    <body> 
     <div class="horz-inputs"> 
      <h2>Top</h2> 
      <label>TextBox 1</label> 
      <input type="text" /> 
      <label>TextBox 2</label> 
      <input type="text" /> 
     </div> 
    </body> 
</html>