skip to Main Content

I have a <form> inside of a <div>

<div>
  <form></form>
</div>

I want the <form> to take up 100% of the parent width taking into account margin and padding. I achieve this by setting box-sizing: border-box

div {
  display: flex;
  align-items: center;
  justify-content: center;
}
form {
  box-sizing: border-box;
  width: 100%;
  margin: 50px;
}

This works. However, in my use case I need the parent div to have flex-direction: column, as <form> will have a sibling <section> above it,

<div>
  <section></section>
  <form></form>
</div>
div {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
form {
  box-sizing: border-box;
  width: 100%;
  margin: 50px;
}

This breaks the desired behavior. The <form> now takes up 100% of the horizontal space, and margin goes outside of it’s parent boundary.

This is the desired effect

enter image description here

2

Answers


  1. I may be wrong, but you can put the flex-direction: column in the form block.

    Login or Signup to reply.
  2. If you really need to align-items: center; in div with flex-direction: column;, you can remove width in form, and just add align-self: stretch;:

    * {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    div {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      /* for demonstration */
      min-height: 40px;
      background-color: gray;
    }
    
    section {
      /* for demonstration */
      min-height: 40px;
      background-color: red;
      align-self: stretch;
    }
    
    form {
      margin: 50px;
      align-self: stretch; /* 👈 */
      /* for demonstration */
      background-color: green;
      min-height: 40px;
    }
    <div>
      <section>Section</section>
      <form>Form</form>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search