[英]Stacking html elements side by side
Flexbox允許輕松調整對齊方式(在兩個軸上),寬度,占據剩余寬度,自動換行或永不自動換行等
您需要一個display: flex
的父容器。 這是flex容器。 現在所有的孩子都是彈性物品 。
這里有兩個例子:
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>
input
和span
元素是“內聯”元素。 它們的寬度僅與它們的內容一樣寬(或者在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.