I am trying youtube.com adaptive grid layout. I could achieve using CSS Grid. But if total number of cards are very less for example 2, card's width increasing to fit entire row. I could avoid this by setting max-width or width, but, gap betwwen cards changing when i change width of browser window.
How to set max-width without increasing the between cardds?
.grid-layout {
padding: 0;
margin: 0;
list-style: none;
border: 1px solid silver;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(5rem, 1fr) );
}
.card {
background: grey;
height: 4rem;
/* Uncommenting below line sets width but gap between card too high*/
/* max-width: 7rem; */
padding: 1px;
margin: 0.5rem;
line-height: 4rem;
color: white;
font-weight: bold;
font-size: 2rem;
text-align: center;
}
<section >
<div >0</div>
<div >1</div>
<!-- <div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>
<div >7</div>
<div >8</div>
<div >9</div>
<div >10</div>
<div >11</div>
<div >12</div>
<div >13</div>
<div >14</div>
<div >15</div>
<div >16</div>
<div >17</div>
<div >18</div>
<div >19</div> -->
</section>
CodePudding user response:
Use grid-gap
with a value of percentage:
.grid-layout {
list-style: none;
border: 1px solid silver;
display: grid;
grid-gap: 20%;
grid-template-columns: 1fr 1fr;
}
.card {
background: grey;
height: 8rem;
padding: 1px;
line-height: 8rem;
color: white;
font-weight: bold;
font-size: 2rem;
text-align: center;
}
<section >
<div >0</div>
<div >1</div>
<!-- <div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>
<div >7</div>
<div >8</div>
<div >9</div>
<div >10</div>
<div >11</div>
<div >12</div>
<div >13</div>
<div >14</div>
<div >15</div>
<div >16</div>
<div >17</div>
<div >18</div>
<div >19</div> -->
</section>
Is this what you want?
CodePudding user response:
auto-fill works as per my expectations instead of auto-fit when columns doesn't wrap.
.grid-layout {
padding: 0;
margin: 0;
list-style: none;
border: 1px solid silver;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(5rem, 1fr) );
}
.card {
background: grey;
height: 4rem;
max-width: 7rem;
padding: 1px;
margin: 0.5rem;
line-height: 4rem;
color: white;
font-weight: bold;
font-size: 2rem;
text-align: center;
}
<section >
<div >0</div>
<div >1</div>
<!-- <div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>
<div >7</div>
<div >8</div>
<div >9</div>
<div >10</div>
<div >11</div>
<div >12</div>
<div >13</div>
<div >14</div>
<div >15</div>
<div >16</div>
<div >17</div>
<div >18</div>
<div >19</div> -->
</section>