垂直居中一个div在另一个div [英] Vertically center a div inside another div
问题描述
我试图 vertical-align:middle
一个div在另一个div,但由于某种原因,它不能正常工作。我做错了什么?
I'm trying to vertical-align: middle
a div inside another div, but for some reason it's not working properly. What am I doing wrong?
#wrapper {
border: 1px solid red;
width: 500px;
height: 500px;
}
#block {
border: 1px solid blue;
width: 500px;
height: 250px;
vertical-align: middle;
}
<div id = 'wrapper'>
<div id = 'block'> I'm Block </div>
<div>
PS:这只是一个例子,所以没有,我实际上不知道div的实际宽度和高度,因为它们是动态的,根据它们的内容,所以请不要margin-top:
PS: This is just an example, so no, I don't actually know the actual width and height of the divs, as they are dynamic, according to their contents, so please no margin-top: 125px, or padding-top: 125px answers, or answers like that.
推荐答案
vertical-align
属性仅适用于 inline-level 和 table-cell 元素( source )。
The vertical-align
property applies only to inline-level and table-cell elements (source). In your code you're working with block-level elements.
尝试使用这个flexbox替代方法:
Try this flexbox alternative:
#wrapper {
border: 1px solid red;
width: 500px;
height: 500px;
display: flex; /* establish flex container */
align-items: center; /* vertically center flex items */
}
#block {
border: 1px solid blue;
width: 500px;
height: 250px;
/* vertical-align: middle; */
}
<div id='wrapper'>
<div id='block'> I'm Block </div>
<div>
要了解有关Flex对齐的详情,请访问:对齐Flex项目的方法
Learn more about flex alignment here: Methods for Aligning Flex Items
浏览器支持 : Flexbox受所有主流浏览器支持,除了IE< 10 。某些最新的浏览器版本(例如Safari 8和IE10)需要供应商字首 。要快速添加前缀,请使用 Autoprefixer 。有关此答案的更多详情。
Browser support: Flexbox is supported by all major browsers, except IE < 10. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add prefixes use Autoprefixer. More details in this answer.
这篇关于垂直居中一个div在另一个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!