将一个 div 垂直居中在另一个 div 中 [英] Vertically center a div inside another div
问题描述
我正在尝试 vertical-align: middle
另一个 div 中的一个 div,但由于某种原因它无法正常工作.我做错了什么?
#wrapper {边框:1px纯红色;宽度:500px;高度:500px;}#堵塞 {边框:1px纯蓝色;宽度:500px;高度:250px;垂直对齐:中间;}
<div id = '块'>我是块 </div> PS: 这只是一个例子,所以不,我实际上并不知道 div 的实际宽度和高度,因为它们是动态的,根据它们的内容,所以请不要留白-top: 125px 或 padding-top: 125px 答案,或类似的答案.
解决方案 vertical-align
属性仅适用于 inline-level 和 table-cell 元素(来源).在您的代码中,您正在使用 块级 元素.
试试这个 flexbox 替代方案:
#wrapper {边框:1px纯红色;宽度:500px;高度:500px;显示:弹性;/* 建立弹性容器 */对齐项目:居中;/* 垂直居中 flex 项目 */}#堵塞 {边框:1px纯蓝色;宽度:500px;高度:250px;/* 垂直对齐:中间;*/}
<div id='块'>我是块 </div>在此处了解有关 Flex 对齐的更多信息:对齐 Flex 项目的方法
浏览器支持: Flexbox 被所有主流浏览器支持, 除了 IE <10.一些最新的浏览器版本,例如 Safari 8 和 IE10,需要 供应商前缀.要快速添加前缀,请使用 Autoprefixer.此答案中的更多详细信息.
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: 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.
解决方案 The vertical-align
property applies only to inline-level and table-cell elements (source). In your code you're working with block-level elements.
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>
Learn more about flex alignment here: Methods for Aligning Flex Items
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屋!
查看全文