簡體   English   中英

輸入 & Label 不要垂直對齊 - 不同的元素寬度

[英]Input & Label Do Not Vertically Align - Different Element Widths

輸入與按鈕和其他元素不對齊的原因是什么?

布局(Firefox Developer Edition)顯示 input 和 label 元素的大小不同,即使它們在同一個 div 中。

在此處輸入圖像描述

是什么原因造成的? 以及如何以優雅的方式對齊它們(例如,無需通過反復試驗改變邊距)?

NewTransaction.js 文件的相關部分: 在此處輸入圖像描述

NewTransaction 的 CSS 文件: 在此處輸入圖像描述

源代碼: https://github.com/yanichik/react-course/tree/main/full-course/expense-tracker-v2

styles歸一化比較好,

在您的代碼中,出現問題的樣式是box-sizing ,我只是將所有元素設置為border-box ,但是您可以只添加box-sizing: border-box; 輸入,它也有效。

 html { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } *, *::before, *::after { -webkit-box-sizing: inherit; -moz-box-sizing: inherit; box-sizing: inherit; }.form { margin-top: 15px; } input { display: flex; width: 100%; } label { display: flex; justify-content: flex-start; } button { display: block; width: 100%; margin-top: 5px; background-color: purple; border-color: purple; color: white; font-weight: bold; }.amount, .description { /* display: flex; */ flex-direction: column; margin-bottom: 5px; margin-top: 5px; }
 <div className="form"> <form onSubmit={submitHandler}> <div class='description'> <label htmlFor="description" pointing="true"> Description </label> <input type="text" id='description' placeholder="Type Something" ref={descrRef}/> </div> <div class='amount'> <label htmlFor="amount" pointing="true"> Amount </label> <input type="number" id='amount' step="0.01" placeholder="$" ref={amountRef} /> </div> <div> <button type="submit">Add Transaction</button> </div> </form> </div>

因為 input 元素在左側和右側都有 2px 的填充,並且作為用戶代理樣式表中的默認值, box-sizing設置為content-box

content-box 為您提供默認的 CSS 框大小調整行為。 如果將元素的寬度設置為 100 像素,則元素的內容框將為 100 像素寬,並且任何邊框或填充的寬度將添加到最終呈現的寬度,使元素寬度超過 100 像素。

您應該使用box-sizing: border-box來解決這個問題。

參考: https://www.w3schools.com/css/css3_box-sizing.asp

您更新的代碼: https://codesandbox.io/embed/expense-tracker-yan-forked-80tfk?fontsize=14&hidenavigation=1&theme=dark

暫無
暫無

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

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