簡體   English   中英

並排堆疊HTML元素

[英]Stacking html elements side by side

我想將4個HTML元素並排放置,總寬度為100%。

<input type="number" name="height" placeholder="weight">
<span>kg</span>
<input type="number" name="weight" placeholder="height">
<span>cm</span>

但是我在堆棧溢出中發現了很多無法正常工作的答案。 我得到這樣的東西...

見中間的w(高度)和h(高度)

Flexbox允許輕松調整對齊方式(在兩個軸上),寬度,占據剩余寬度,自動換行或永不自動換行等

您需要一個display: flex的父容器。 這是flex容器。 現在所有的孩子都是彈性物品

CSS技巧對Flexbox有一個強大的備忘單

這里有兩個例子:

  • 輸入占據了跨度未占用的空間(應該是標簽元素嗎?)- Codepen
  • 每個元素大約占寬度的25%,減去每個輸入及其標簽之間所需的邊距-Codepen

 html { box-sizing: border-box; } * { box-sizing: inherit; } body { margin: 0; } .container { display: flex; padding: 2rem 1rem; background-color: tomato; } .container input { flex-grow: 1; } .container span { margin: 0 4rem 0 0.5rem; } .container span:last-of-type { margin-right: 0; } 
 <div class="container"> <input type="number" name="height" placeholder="weight"> <span>kg</span> <input type="number" name="weight" placeholder="height"> <span>cm</span> </div> 

 html { box-sizing: border-box; } * { box-sizing: inherit; } body { margin: 0; } .container { display: flex; padding: 2rem 1rem; background-color: beige; } .container input, .container span { width: calc(25% - 0.5rem); /* half of the margin set below */ } .container span { margin-left: 1rem; } 
 <div class="container"> <input type="number" name="height" placeholder="weight"> <span>kg</span> <input type="number" name="weight" placeholder="height"> <span>cm</span> </div> 

inputspan元素是“內聯”元素。 它們的寬度僅與它們的內容一樣寬(或者在input的情況下,與您告訴他們的一樣寬)。 您已經將它們並排放置,但是您需要將它們視為“塊”元素以能夠設置width以便它們總共可以占用100%的可用寬度。這一頁。

您需要研究block vs. inline元素和CSS Box Model才能開始了解默認情況下網頁中布局的工作方式。

這是一個導致input字段擴展以填充空白的示例:

 input { display:inline-block; /* Allow the inline element to be sized as a block element */ width:calc(50% - 2.5em); /* Each will be 50% of the width of the parent - roughly 2.5 characters */ } 
 <input type="number" name="height" placeholder="weight"> <span>kg</span> <input type="number" name="weight" placeholder="height"> <span>cm</span> 

或者,如果您只是希望寬度正常,但希望所有4個元素都在可用寬度內居中,則需要告訴父元素如何水平對齊其子元素,可以使用text-align

 .center { text-align:center; } 
 <div class="center"> <input type="number" name="height" placeholder="weight"> <span>kg</span> <input type="number" name="weight" placeholder="height"> <span>cm</span> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM