Html 如何在div底部放置图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17934332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:37:34  来源:igfitidea点击:

How do I position an image at the bottom of div?

csshtmlalignment

提问by Dustin Lee

I want an html image to be flush with the bottom of a div tag. I can't seem to find a way to accomplish this.

我想要一个 html 图像与 div 标签的底部齐平。我似乎无法找到一种方法来实现这一点。

Here is my HTML:

这是我的 HTML:

<div class="span8">
  <img src="/img/play-shot1.jpg" class="text-center shadow">
</div>

The problem is that the div is nested within other divs that have padding or margins.

问题是 div 嵌套在其他具有填充或边距的 div 中。

回答by Matt Lambert

Add relative positioning to the wrapping div tag, then absolutely position the image within it like this:

将相对定位添加到包装 div 标签,然后将图像绝对定位在其中,如下所示:

CSS:

CSS:

.div-wrapper {
    position: relative;
    height: 300px;
    width: 300px;
}

.div-wrapper img {
    position: absolute;
    left: 0;
    bottom: 0;
}

HTML:

HTML:

<div class="div-wrapper">
    <img src="blah.png"/>
</div>

Now the image sits at the bottom of the div.

现在图像位于 div 的底部。

回答by ajrussellaudio

Using flexbox:

使用弹性盒:

HTML:

HTML:

<div class="wrapper">
    <img src="pikachu.gif"/>
</div>

CSS:

CSS:

.wrapper {
    height: 300px;
    width: 300px;
    display: flex;
    align-items: flex-end;
}

As requested in some comments on another answer, the image can also be horizontally centred with justify-content: center;

根据对另一个答案的一些评论的要求,图像也可以水平居中 justify-content: center;