1

Please see this minimum example:

body {
  display: grid;
  place-items: center;
}

div {
  border: 1px solid red;
}

input {
  max-width: 260px;
  width: 100%;
}
<div>
  <input type="text">
</div>

I want my <input> element to have 260px width when available, and when on the small screen, use 100% width.

However, it's not working, why is this happening?

Joseph
  • 3,974
  • 7
  • 34
  • 67

1 Answers1

0

Box Sizing

Try adding box-sizing: border-box; to the input styles.

The default box-sizing (content-box) doesnt take the padding into consideration when rendering size. By default, most browsers add padding to inputs in the base browser styles.

This means if you set the width of something to 100px but that something has a left padding of 5px, the total rendered width will be 105px!

This is why a LOT of CSS resets add * { box-sizing: border-box; } to the reset because it is arguably more intuative.

You can read more about box-sizing if you're interested.

body {
  display: grid;
  place-items: center;
}

div {
  border: 1px solid red;
}

input {
  box-sizing: border-box;
  max-width: 100%;
  width: 260px;
}
<div>
  <input type="text">
</div>
cam
  • 3,179
  • 1
  • 12
  • 15
  • Thank you, but the rendered `` element is still not `260px`, do you have any idea? – Joseph Feb 26 '21 at 05:33
  • Oh that's because you're using `max-width` which sets the *maximum* width, not the actual width. Use `width: 260px` – cam Feb 26 '21 at 05:42
  • I've updated my answer, you need to flip your width and max-width values around. – cam Feb 26 '21 at 05:42
  • But why `max-width: 260px;` + `width: 100%;` won't render `260px`? – Joseph Feb 26 '21 at 05:46
  • 1
    Because it's 100% of the parent container (the div), which when positioned in a grid isnt automatically 100%. Try adding `width: 100%` to the parent div and see what happens. – cam Feb 26 '21 at 05:55