0

Imagine I have a grid with couple of columns and some gap between them

.my-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 3px;
}

Then I want to place an input to both cells. But this input has to be styled with some border and so on. It's convenient for me to wrap it in a flex container:

<div class="flex-container">
  <input type="text">
</div>

.flex-container {
  display: flex;
  flex-direction: row;
  width: 100%;

  border: 1px solid #cc0384;
  border-radius: 5px;
  padding: 5px;

  > input {
    flex-grow: 1;
    border: none;
    outline: none;
  }
}

And then I just want to place such inputs into the cells of a grid.

<div class="my-grid">
  <div class="flex-container">
    <input type="text">
  </div>

  <div class="flex-container">
    <input type="text">
  </div>
</div>

I expect that there will be a couple of inputs which are separated by gap. But suddenly they are intersected with each other. It seems that an internal input takes the whole width of grid cell and flex-box containers are spilled over the borders of grid cell. What is the reason and how to fix that?

Example on JSFiddle

Don Tomato
  • 3,311
  • 3
  • 30
  • 48

1 Answers1

1

Your padding is causing this problem. You say width: 100% and padding: 5px so the overall width is 100% + 2 * 5px = 100% + 10px (5px on the left and right). To avoid that the width is increasing over 100%, you can say box-sizing: border-box. So your flex-container will have a overall width of 100%, but the padding is already calculated.

You can use border-box to prevent that borders and paddings will "spread" above your configured size (width and height).

.flex-container {
  display: flex;
  flex-direction: row;
  width: 100%;

  border: 1px solid #cc0384;
  border-radius: 5px;
  padding: 5px;
  box-sizing: border-box;
}

Here are some helpful links:

CSS Box Sizing

box-sizing CSS

Edit: Added a code example.

.parent{    
    display: block;
    position: relative;
    width: 200px;
    height: 200px;
    background: red;
    padding: 20px;
}

.is-border-box{
    box-sizing: border-box;
}

.fullsized-child{
    position: relative;
    width: 100%;
    height: 100%;
    background: blue;
    color: #fff;
}
<div class="parent">
    <div class="fullsized-child">Without box-sizing: border-box. The parent size is stretched from 200x200px to 240x240px.</div>
</div>
<br>
<div class="parent is-border-box">
    <div class="fullsized-child">Without box-sizing: border-box.
    The parent size is remains 200x200px.
    </div>
</div>
michaelT
  • 1,533
  • 12
  • 41