Home > OS >  Prevent input from overflow grid parent
Prevent input from overflow grid parent

Time:12-03

Consider the following snippet:

#parent {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  width: 275px;
  border: 2px solid green;
  padding: 10px;
}
input {
  background-color: hotpink;
}
<div id="parent">
  <input />
  <input />
  <input />
  <input />
</div>

If you run the snippet, you will find that the inputs overflow the parent div along the x-axis and refuses to fit inside the div (tested in Chromium-based Edge). Basically, when you give the parent with display: grid a fixed width, the input children don't seem to fit.

I've tried all the properties I could think of, but none of them seemed to keep the inputs where they belong (I expect a nice 2x2 grid where the children fit evenly into the grid). How can I keep the inputs in the grid?

CodePudding user response:

You could use a percentage of the overall parents width in your grid template column for the parents css. Being you have two items, you can divide 100% by the amount of items and use that percentage grid-template-columns: repeat(2, 50%);

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

#parent {
  display: grid;
  grid-template-columns: repeat(2, 50%);
  grid-template-rows: repeat(2, 1fr);
  width: 275px;
  border: 2px solid green;
  padding: 10px;
}

input {
  background-color: hotpink;
}
<div id="parent">
  <input />
  <input />
  <input />
  <input />
</div>

CodePudding user response:

The input width is depends on its size if there is no other width style on it, and the default of size is 20. Info from MDN

MDN Link

  • Related