发现很难使堆叠式div响应

时间:2018-10-11 01:51:51

标签: css responsive-design responsive

.container{
  border: 1px solid black;
  width: 13em;
  
}
.animal:nth-child(n+2){
  margin-left: -5em;
}
.animal{
  width: 6em;
  height:6em;
  display: inline-block;
  background: yellow;
  border: 1px solid black;
  border-radius: 6px;
}

.container2{
  border: 1px solid black;
  width: 14em;
  height: 120px;
}

.animal1,.animal2,.animal3,.animal4,.animal5,.animal6,.animal7,.animal8{
  width: 6em;
  height: 6em;
  background: yellow;
  border: 1px solid black;
  border-radius: 6px;
  display: inline-block;
}

.animal1{
  position: absolute;
  left: 1em;
}
.animal2{
  position: absolute;
  left: 3em;
}
.animal3{
  position: absolute;
  left: 6em;
}
.animal4{
  position: absolute;
  left: 9em;
}
.animal5{
  position: absolute;
  left: 12em;
}
.animal6{
  position: absolute;
  left: 15em;
}
.animal7{
  position: absolute;
  left: 18em;
}
.animal8{
  position: absolute;
  left: 21em;
}
<html>
  <body>
    <h2>Case1</h2>
    <div class="container">
      <div class="animal">Dog</div>
      <div class="animal">Cat</div>
      <div class="animal">Mouse</div>
      <div class="animal">Duck</div>
      <div class="animal">Fish</div>
      <div class="animal">Fish</div>
      <div class="animal">Fish</div>
      <div class="animal">Fish</div>
      <div class="animal">Mouse</div>
      <div class="animal">Cat</div>
    </div>
    <br><br>
    <h2>Case2</h2>
    <div class="container2">
      <div class="animal1">Dog</div>
      <div class="animal2">Cat</div>
      <div class="animal3">Mouse</div>
      <div class="animal4">Duck</div>
      <div class="animal5">Fish</div>
      <div class="animal6">Fish</div>
      <div class="animal7">Fish</div>
      <div class="animal8">Fish</div>
    </div>
  </body>
</html>

有些div相互堆叠。我用两种方式实现堆栈:(1)负边距,和(2)position:absolute,剩余增量。但是,如果我使用负边距,第二行的div将溢出。如果我使用position:absolute,则当容器较小时,div也将溢出。如何使堆叠的div响应?我可以使其响应100格吗?

1 个答案:

答案 0 :(得分:1)

CSS-Grid解决方案可以为您服务。

.container {
  border: 1px solid black;
  width: 13em;
  display: grid;
  grid-template-columns: repeat(4, 2em); /* Tweak me! */
}

/* A random media query */
@media (min-width: 1200px) {
  .container {
    width: 26em;
    grid-template-columns: repeat(8, 2em);
  }
}

.animal {
  width: 6em;
  height: 6em;
  display: inline-block;
  background: yellow;
  border: 1px solid black;
  border-radius: 6px;
}
<div class="container">
  <div class="animal">Dog</div>
  <div class="animal">Cat</div>
  <div class="animal">Mouse</div>
  <div class="animal">Duck</div>
  <div class="animal">Fish</div>
  <div class="animal">Fish</div>
  <div class="animal">Fish</div>
  <div class="animal">Fish</div>
  <div class="animal">Mouse</div>
  <div class="animal">Cat</div>
</div>

根据您的需求调整grid-template-columns

要获得响应,只需在媒体查询中进行更改即可。我在上面的示例中对此进行了演示。