Home > Software design >  How to prevent Input element from exceeding width of CSS grid column
How to prevent Input element from exceeding width of CSS grid column

Time:05-27

I want to use CSS grid to manage the layout of multiple forms. The goal is to use a two-column grid with the label elements in the left column and the input elements in the right column. The left column's width needs to be sized to fit the widest label, and the right column should take up the remainder of the space. This is the grid column template I'm using:

grid-template-columns: max-content 1fr;

The issue that I'm facing is that the input element will frequently exceed the width of the right column. Unfortunately, setting max-width to 100% on the input element does not constrain its size to the column's width. If I set the width to 100%, that does constrain the size, but as the responsive form gets wider, a 100% width on the input is too wide from a design perspective.

This is the markup:

<body>
<div >
  <label>This is label 1</label>
  <input type="text" maxlength="100">
  <label>This is label 2</label>
  <input type="text" maxlength="100">
  <label>This is label 3 which is a bit longer</label>
  <input type="text" maxlength="100">
  <label>This is label 4</label>
  <input type="text" maxlength="100">
</div>
</body>

This is the CSS:

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

.container {
  width: 300px;
/*   width: 1300px; */
  margin: 2rem auto;
  background-color:lightblue;
  display: grid;
  grid-template-columns: max-content 1fr;
  align-items: center;
  grid-column-gap: 24px;
  grid-row-gap:8px;
}

input {
  padding: .5rem .5rem;
  max-width:100%;
/*   width: 12rem; */
  justify-self: end;
}

This is a CodePen.

Q: How do I limit the width of the input to about 200 pixels and keep it flushed right? At the same time, as the form gets narrower, it should never exceed the width of the grid column.

CodePudding user response:

.container input {min-width: 0;}

  • Related