實作HTML元素在一個div中的水平對齊
P粉431220279
2023-08-22 00:03:55
<p>我有三個HTML對象,想要在一個容器div中將Previous按鈕放在左側,Next按鈕放在右側,span放在中間。 </p>
<pre class="brush:php;toolbar:false;"><PREVIOUS> |SPAN| <NEXT></pre>
<p><br /></p>
<pre class="snippet-code-css lang-css prettyprint-override"><code> #btnPrevious
{
float:left;
}
#spanStage
{
font-weight:bold;
vertical-align:middle;
}
#btnNext
{
float:right;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div>
<input type="button" value="Previous" id="btnPrevious"/>
<span id="spanStage">Stage 5</span>
<input type="button" value="Next" id="btnNext"/>
</div></code></pre>
<p><br /></p>
「display:flex」樣式是讓這些元素在同一行的好方法。無論div中有什麼類型的元素。特別是如果輸入類別是form-control,其他解決方案如bootstrap,inline-block將無法很好地工作。
範例:
有關flexbox的更多詳細資訊:https://css-tricks.com/snippets/css/a-guide-to-flexbox/
#flex-direction: row, column
justify-content: flex-end, center, space-between, space-around
#align-items: stretch, flex-start, flex-end, center
只需將
text-align: center
新增至您的包裝器中,以設定所有非浮動/非定位子元素的水平對齊:<span>
預設為內聯元素。因此,您可以在它們上使用display:block
並適當地對其進行樣式設置,或稍微調整父元素的樣式。由於除了<span>
和<button>
之外沒有其他子元素,所以最好使用這個簡單的解決方案。請注意,
text-align:<value>
會從父元素繼承,因此如果您想在包裝器中包含其他內容,您應該檢查text-align:center
是否適合您。否則,在特定元素中使用text-align:<value>
,其中value
可以是left
、right
、center
或justify
。JSFiddle示範
#