如何使用flex将图像与div的底部对齐?

时间:2018-12-12 17:53:52

标签: html css css3 flexbox

我有一个父容器,其中包含一些子元素,例如基于内容的不同高度的段落。我正在尝试使用NameError: name 'db' is not defined将图像对齐到垂直轴的底部,因此它不会影响父容器中的其他项目并将图像放置到父容器的底部,但不会不行。

但是,当我使用justify-self: flex-end时,它可以正常工作并将整个内容推到底部,但是我只希望仅将图像对齐到底部。我在做什么错,我该如何解决?

justify-content: flex-end
.parent-container {
    display: flex;
}
.parent-container > div {
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    margin: 0 10px;
    /*justify-content: flex-end;*/
    flex: 1;
}
.img-container {
    justify-self: flex-end;
}
.img-container img {
    width: 100%;
    justify-self: flex-end;
}

JSFiddle:https://jsfiddle.net/TheAmazingKnight/upay1rod/

3 个答案:

答案 0 :(得分:1)

loop容器中包装h3p并将div添加到justify-content: space-between;

CSS:

.parent-container > div

HTML:

.parent-container {
    display: flex;
}

.parent-container > div {
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    margin: 0 10px;
    justify-content: space-between;
    flex: 1;
}

答案 1 :(得分:1)

如果您只是更改CSS,那么它将起作用。我添加了heigh:100%;,未对justify-content:flex-end;进行注释,并将.parent-container > div重新分配给div.img-container

    .parent-container {
        display: flex;
    }

    div.img-container {
        display: flex;
        flex-direction: column;
        flex-wrap: wrap;
        margin: 0 10px;
        height: 100%;
        justify-content: flex-end;
        flex: 1;
    }

    img {
        width: 100%;
        justify-self: flex-end;
    }

答案 2 :(得分:1)

取消注释justify-content:flex-end;并添加margin-top:在img容器上自动添加

.parent-container {
    display: flex;
}
.parent-container > div {
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    margin: 0 10px;
    justify-content: flex-end;
    flex: 1;
}
.img-container {
    margin-top: auto;  /* added */
}
.img-container img {
    width: 100%;
    justify-self: flex-end;
}
<div class="parent-container">
  <div>
    <h3>header 1</h3>
    <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
    <div class="img-container">
      <img src="https://place-hold.it/300x500">
    </div>
  </div>

  <div>
    <h3>header 2</h3>
    <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
    <div class="img-container">
      <img src="https://place-hold.it/300x500">
    </div>
  </div>

  <div>
    <h3>header 3</h3>
    <p>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</p>
    <div class="img-container">
      <img src="https://place-hold.it/300x500">
    </div>
  </div>
</div>