A. L
A. L

Reputation: 12669

css grid to justify contents center if row is not full

So I was wondering if it was possible for display: grid to center its items at the center like a flexbox if the row isn't filled up.

Example:

for (let i = 0; i < 3; i++)
{
 
  $("#main").append($("<div class='item'>test</div>"))
  $("#flex").append($("<div class='flex-item'>test</div>"))
}
#main {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
}

.item {
  border: 1px solid black;
  height: 100px;
}


#flex {
  display: flex;
  width: 100%;
  justify-content: center;
}

.flex-item {
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
</div>

<div id="flex">
  
</div>

Upvotes: 3

Views: 3107

Answers (1)

Suresh Ponnukalai
Suresh Ponnukalai

Reputation: 13998

Apply auto instead 1fr in grid-template-columns. Then apply your desired width for your items. It will make the desired result.

 #main {
   display: grid;
   grid-template-columns: repeat(6, auto);
   width: 100%;
   height: 100%;
   align-items: center;
   justify-content: center;  
}
.item {
   border: 1px solid black;
   height: 100px;
   width:100px;
}

DEMO

UPDATE:

If you don't want to fix the column width then use the vw to apply dynamic width based on your screen.

.item {
   border: 1px solid black;
   content: "test";
   height: 100px;
   width:16vw;
}

DEMO

Upvotes: 2

Related Questions