Explanation About Centering a Text Input Field with CSS

I’ve been working on the Survey Form challenge and have come across an issue that I can’t seem to find an answer for.

I created a main container div to house the survey, much like in the example. Whenever I create a new div inside the container and center it using margin: auto; most things work fine. Whenever I try to do the same thing with the text input field, it is always closer to the right side of the container than the left side.

I have found ways around this, but I am trying to get an explanation as to why it doesn’t work in this manner to better understand what I can do going forward.

Code Pen Link to Test Project

Any help or information would be greatly appreciated.

The browser uses a set of default styles. One of these styles is to do with how it interprets the box sizing – when you add padding and borders to anything, that is added to the total width.

So if you have something set to 100px wide, and it has a border of 1px all round and padding of 10px at the side that means it’s actually 122px wide.

What you’re seeing when your web page renders is due to box-sizing being the default. To fix it you can check the sizes of padding/borders and factor those into the calculation of widths or padding or whatever.

Doing this is a huge pain, and is almost impossible with layouts that are not in pixels (ie most modern layouts). It is almost always undesirable behaviour, so setting this at the top of your CSS will turn it off:

*, *::before, *::after {
  box-sizing: border-box;
}

What that does is say that for every element on the page, the width should include the border and padding widths.

So if you have something set to 100px wide, and it has a border of 1px all round and padding of 10px at the side, it’s still 100px wide.

This should immediately fix your issue.