[英]Input & Label Do Not Vertically Align - Different Element Widths
输入与按钮和其他元素不对齐的原因是什么?
布局(Firefox Developer Edition)显示 input 和 label 元素的大小不同,即使它们在同一个 div 中。
是什么原因造成的? 以及如何以优雅的方式对齐它们(例如,无需通过反复试验改变边距)?
源代码: 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
来解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.