Html 将文本与 div 的底部对齐
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17123327/
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
Align text to the bottom of a div
提问by parascus
I tried to align my text to the bottom of a div from other posts and answers in Stack Overflow I learned to handle this with different CSS properties. But I can't get it done. Basically my HTML code is like this:
我尝试将我的文本与 Stack Overflow 中其他帖子和答案中的 div 底部对齐,我学会了使用不同的 CSS 属性来处理这个问题。但我做不到。基本上我的 HTML 代码是这样的:
<div style='height:200px; float:left; border:1px solid #ff0000; position:relative;'>
<span style='position:absolute; bottom:0px;'>A Text</span>
</div>
The effect is that in FF I just get vertical line (the div in a collapsed way) and the text is written next to it. How can I prevent the div
collapsing but having the width fitting to the text?
效果是在 FF 中我只得到垂直线(折叠方式的 div)并且文本写在它旁边。如何防止div
折叠但宽度适合文本?
回答by Mr. Alien
Flex Solution
柔性解决方案
It is perfectly fine if you want to go with the display: table-cell
solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;
. flex
is something which has a decent support.
如果您想使用display: table-cell
解决方案,那完全没问题。但是,与其破解它,我们还有更好的方法来使用display: flex;
. flex
是有体面支持的东西。
.wrap {
height: 200px;
width: 200px;
border: 1px solid #aaa;
margin: 10px;
display: flex;
}
.wrap span {
align-self: flex-end;
}
<div class="wrap">
<span>Align me to the bottom</span>
</div>
In the above example, we first set the parent element to display: flex;
and later, we use align-self
to flex-end
. This helps you push the item to the end of the flex
parent.
在上面的例子中,我们首先将父元素设置为display: flex;
,然后我们使用align-self
to flex-end
。这有助于您将项目推送到flex
父项的末尾。
Old Solution (Valid if you are not willing to use flex
)
旧解决方案(如果您不愿意使用则有效flex
)
If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell;
with vertical-align: bottom;
is enough
如果要将文本对齐到底部,则不必为此编写这么多属性,使用display: table-cell;
withvertical-align: bottom;
就足够了
div {
display: table-cell;
vertical-align: bottom;
border: 1px solid #f00;
height: 100px;
width: 100px;
}
<div>Hello</div>
回答by Zequez
You now can do this with Flexbox justify-content: flex-end
now:
你现在可以用 Flexbox 做到这一点justify-content: flex-end
:
div {
display: flex;
justify-content: flex-end;
align-items: flex-end;
width: 150px;
height: 150px;
border: solid 1px red;
}
<div>
Something to align
</div>
Consult your Caniuseto see if Flexbox is right for you.
咨询您的 Caniuse,看看 Flexbox 是否适合您。