CurtisB
CurtisB

Reputation: 29

CSS Grid auto-fit column automatically wraps

from the example I have three columns, when resized at a certain view-port it will wrap onto the next row, how can I target that individual div and make it fill the available width?

.boxes {
  color: white;
  display: grid;
  grid-gap: 20px;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}

.box {
  background-color: blue;
  padding: 10px;
}
<section class = "boxes">
  <div class="box">
    <p>Box 1</p>
  </div>
  <div class="box">
    <p>Box 2</p>
  </div>
  <div class="box">
    <p>Box 3</p>
  </div>
</section>

Codepen:

CodePen

Upvotes: 2

Views: 1112

Answers (2)

Omer
Omer

Reputation: 3486

Limit columns by max-width

you can stay with grid, but it look good only if you stay with 2 columns.

for more columns its more complicated and you can define what you want, to use grid or to use flex for convenient way.

html {
  box-sizing: border-box;
}

body {
  background-color: white;
  color: white;
}

.boxes {
  display: grid;
  grid-gap: 20px;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  max-width: 700px;
  margin: 0 auto;
  text-align: center;
}

.box {
  background-color: blue;
  padding: 10px;
}

.box:last-child:nth-child(odd) {
  grid-column: 1/3;
 }
<!DOCTYPE html>
<html>

<head>
  <title>Column Resize</title>
  <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
  <section class="boxes">
    <div class="box">
      <p>Box 1</p>
    </div>
    <div class="box">
      <p>Box 2</p>
    </div>
    <div class="box">
      <p>Box 3</p>
    </div>
  </section>
</body>

</html>

Upvotes: 0

Temani Afif
Temani Afif

Reputation: 272947

You need flexbox for this:

body {
  color: white;
}

.boxes {
  display: flex;
  flex-wrap: wrap;
}

.box {
  background-color: blue;
  padding: 10px;
  min-width: 250px;
  box-sizing:border-box;
  margin: 10px;
  flex-grow: 1;
}
<section class="boxes">
  <div class="box">
    <p>Box 1</p>
  </div>
  <div class="box">
    <p>Box 2</p>
  </div>
  <div class="box">
    <p>Box 3</p>
  </div>
</section>

Upvotes: 1

Related Questions