繁体   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