Home > Back-end >  Input & Label Do Not Vertically Align - Different Element Widths
Input & Label Do Not Vertically Align - Different Element Widths

Time:10-11

What's the reason the inputs do not align with the button and other elements?

Layout (Firefox Developer Edition) shows that the sizes of input and label elements differ even though they are in the same div.

enter image description here

What causes this? And how to align them in an elegant way (without changing margin through trial and error for example)?

Relevant section of NewTransaction.js file: enter image description here

CSS file of NewTransaction: enter image description here

SOURCE CODE: https://github.com/yanichik/react-course/tree/main/full-course/expense-tracker-v2

CodePudding user response:

Because the input element has padding of 2px on both left and right, and as default in user agent stylesheet, box-sizing is set to content-box.

content-box gives you the default CSS box-sizing behavior. If you set an element's width to 100 pixels, then the element's content box will be 100 pixels wide, and the width of any border or padding will be added to the final rendered width, making the element wider than 100px.

You should use box-sizing: border-box to overcome this issue.

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

Your updated code: https://codesandbox.io/embed/expense-tracker-yan-forked-80tfk?fontsize=14&hidenavigation=1&theme=dark

CodePudding user response:

It's better to normalize the styles,

in your code the style that made problem was box-sizing, I just set for all element to border-box, however you can just add box-sizing: border-box; to input and it works too.

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>

  • Related