仅使用CSS在<div>中堆叠一些子元素

时间:2016-11-07 18:49:28

标签: html5 css3

目前我的网页的一部分看起来像这样

--------------------------------------
| ----------  ----------  ---------- |
| |  img   |  |   img  |  |  img   | | 
| |        |  |        |  |        | | 
| ----------  ----------  ---------- |                                    
| ----------  ----------  ---------- |
| |   h4   |  |   h4   |  |   h4   | |
| ----------  ----------  ---------- |
| ----------  ----------  ---------- |
| |    p   |  |    p   |  |    p   | |
| ----------  ----------  ---------- |
--------------------------------------

当视口宽度为320px宽时,我希望列子元素重新对齐(通过媒体查询,即纯CSS)

----------------------------
| ----------  ----------   |
| |  img   |  |   h4   |   | 
| |        |  ----------   |
| ----------  ----------   | 
|             |    p   |   |
|             ----------   |                               
| ----------  ----------   |
| |  img   |  |   h4   |   | 
| |        |  ----------   |
| ----------  ----------   | 
|             |    p   |   |
|             ----------   |     
----------------------------

(以及第3个img,h4和p以下。)有没有办法只在CSS中执行此操作?我的HTML:

<section>
  <div class="row">
    <div class="column">
      <img src="1">
      <h4>1</h4>
      <p>1</p>
    </div>
    <div class="column">
      <img src="2">
      <h4>2</h4>
      <p>2</p>
    </div>
    <div class="column">
      <img src="3">
      <h4>3</h4>
      <p>3</p>
    </div>
  </div>
</section>

CSS:

.row {
   display: flex;
   justify-content: center;
   margin: 0 auto;
}

.row .column {
    width: 361px;
    height: 283px;
    margin: 9.5% 5px 5px 5px;
}

.row .column h4 {
    margin: 10%;
}

.row .column p {
    margin: 10% 0 0 0;
}

1 个答案:

答案 0 :(得分:1)

如果您为p提供50%的左边距,则可以这样工作,您可以将column设置为display: flex

&#13;
&#13;
.row {
  display: flex;
  justify-content: center;
  margin: 0 auto;
}
.row .column {
  width: 33.33%;
  border: 1px solid black;
}
.row .column img {
  width: 80%;
  margin: 0 10%;
}
.row .column h4 {
  margin: 10% 0;
  background: yellow;
}
.row .column p {
  margin: 10% 0;
  background: lime;
}
@media screen and (max-width: 400px) {
  .row {
    flex-wrap: wrap;
  }
  .row .column {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
  }
  .row .column * {
    width: 50%;
  }
  .row .column img {
    width: 30%;
    margin: 0 10%;
  }
  .row .column p {
    margin-left: 50%;
  }  
}
&#13;
<section>
  <div class="row">
    <div class="column">
      <img src="http://placehold.it/100">
      <h4>1</h4>
      <p>1</p>
    </div>
    <div class="column">
      <img src="http://placehold.it/100">
      <h4>2</h4>
      <p>2</p>
    </div>
    <div class="column">
      <img src="http://placehold.it/100">
      <h4>3</h4>
      <p>3</p>
    </div>
  </div>
</section>
&#13;
&#13;
&#13;