[如果项目少,如何限制网格容器的宽度,但是如果项目多,如何拉伸以填充父容器?

问题描述 投票:0回答:1

我有一个按钮,当按下该按钮时,它会向网格添加项目,此刻看起来像这样:

enter image description here

如您所见,网格容器被拉伸了全宽...但是我希望它与按钮的宽度相同,并且仅在添加更多项时才被拉伸,例如:

enter image description here

CSS网格有可能吗?

document.querySelector('#add').addEventListener('click', function() {
	document.querySelector('.grid').insertAdjacentHTML('afterbegin', '<div class="item"></div>');
});
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  grid-gap: 20px;
  
  background: #777;
  padding: 20px;
}

.item {
  height: 100px;
  background: white;
}

#add {
  width: 100px;
  height: 100px;
  
  background: #333;
  color: white;
  font-size: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  
}
<div class="grid">
  <div id="add">+</div>
</div>
css css-grid
1个回答
0
投票

您可以使用flexbox对此进行近似:

document.querySelector('#add').addEventListener('click', function() {
	document.querySelector('.grid').insertAdjacentHTML('afterbegin', '<div class="item"></div>');
});
.grid {
  display: flex;
  flex-wrap:wrap;
  max-width:max-content; /* This will limit the container */
  
  align-items: center;
  background: #777;
  padding:10px;
}
/* This is a hack to limit the grow effect*/
.grid:after {
  content:"";
  flex-grow:999;
}
/**/
.item {
  height: 100px;
  background: white;
  flex-grow:1;
  width:100px;
  margin:10px;
}

#add {
  width: 100px;
  height: 100px;
  
  background: #333;
  color: white;
  font-size: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
  
}
<div class="grid">
  <div id="add">+</div>
</div>

或者您考虑使用一些JS,因为您已经在使用JS:

var i=1;
document.querySelector('#add').addEventListener('click', function() {
  document.querySelector('.grid').insertAdjacentHTML('afterbegin', '<div class="item"></div>');
  i++;
  document.querySelector('.grid').style.maxWidth=(i*100 + (i-1)*20)+'px';
});
.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  grid-gap: 20px;
  background: #777;
  padding: 20px;
  max-width:100px;
}

.item {
  height: 100px;
  background: white;
}

#add {
  width: 100px;
  height: 100px;
  background: #333;
  color: white;
  font-size: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 50%;
}
<div class="grid">
  <div id="add">+</div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.