如何使网格中的项目适合一行?

时间:2019-03-01 10:07:14

标签: html css css3 css-grid

我正在尝试使3个div适合网格内。但是,我想将代码重用于可能有多个网格的其他网格。这可能还是我应该单独编写代码?

  <div class="div-wrapper">
    <div class="div1"></div>
    <div class="div2"></div>
    <div class="div3"></div>
  </div>

.div-wrapper{
  display:grid;
  grid-template-columns:repeat(3,1fr);
  grid-gap:5px;
  width:100%;
  height:10vh;
  background:black;
}

但是,我想将上面的代码用于内部包含3个以上div的其他包装器,例如

    <div class="div-wrapper">
      <div class="div1"></div>
      <div class="div2"></div>
      <div class="div3"></div>
      <div class="div4"></div>
      <div class="div5"></div>
    </div>

3 个答案:

答案 0 :(得分:3)

那就不要说你有3列。

您可以像这样使用grid-auto-flow

.div-wrapper {
  display: grid;
  grid-auto-flow: column;
  grid-gap: 5px;
  width: 100%;
  height: 10vh;
}

然后它的行为类似于flex,并且您可以具有自动的列数。

答案 1 :(得分:0)

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="d-flex flex-row justify-content-between my-flex-container">
  <div class="p-2 my-flex-item">1</div>
  <div class="p-2 my-flex-item">2</div>
  <div class="p-2 my-flex-item">3</div>
</div>


<div class="d-flex flex-row justify-content-between my-flex-container">
  <div class="p-2 my-flex-item">1</div>
  <div class="p-2 my-flex-item">2</div>
  <div class="p-2 my-flex-item">3</div>
  <div class="p-2 my-flex-item">4</div>
  <div class="p-2 my-flex-item">5</div>
</div>

使用bootstrap flex列 更多信息,请点击此处https://getbootstrap.com/docs/4.1/utilities/flex/

<div class="d-flex flex-row justify-content-between my-flex-container">
     <div class="p-2 my-flex-item">1</div>
     <div class="p-2 my-flex-item">2</div>
     <div class="p-2 my-flex-item">3</div>
</div>

<div class="d-flex flex-row justify-content-between my-flex-container">
     <div class="p-2 my-flex-item">1</div>
     <div class="p-2 my-flex-item">2</div>
     <div class="p-2 my-flex-item">3</div>
     <div class="p-2 my-flex-item">4</div>
     <div class="p-2 my-flex-item">5</div>
</div>

答案 2 :(得分:0)

使用BootStrap“ row”类请参考here

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<div class="row">
       <div class="p-2">one</div>
       <div class="p-2">two</div>
       <div class="p-2">three</div>
</div>

这将显示在行中。