CSS flexbox 垂直/水平居中图像,无需明确定义父高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25832340/
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
CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height
提问by John
With onlythe parent div
and the child img
elements as demonstrated below how do I vertically andhorizontally center the img
element while explicitly notdefining the height
of the parent div
?
与只有父div
和子img
元素作为证明下面我怎么垂直和水平居中的img
元素,同时明确不定义height
父div
?
<div class="do_not_define_height">
<img alt="No, he'll be an engineer." src="theknack.png" />
</div>
I'm not too familiar with flexbox so I'm okay if flexbox itself fills up the full height, but not any other unrelated properties.
我对 flexbox 不太熟悉,所以如果 flexbox 本身填满了整个高度,但没有任何其他不相关的属性,我就可以了。
采纳答案by John
Without explicitly defining the height
I determined I need to apply the flex
value to the parent andgrandparent div
elements...
没有明确定义height
我决定我需要将flex
值应用于父元素和祖父div
元素......
<div style="display: flex;">
<div style="display: flex;">
<img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>
If you're using a single element (e.g. dead-centered text in a single flex
element) use the following:
如果您使用单个元素(例如单个元素中的死居中文本flex
),请使用以下内容:
align-items: center;
display: flex;
justify-content: center;
回答by Danield
Just add the following rules to the parent element:
只需将以下规则添加到父元素:
display: flex;
justify-content: center; /* align horizontal */
align-items: center; /* align vertical */
Here's a sample demo(Resize window to see the image align)
这是一个示例演示(调整窗口大小以查看图像对齐)
Browser supportfor Flexbox nowadays is quite good.
For cross-browser compatibility for display: flex
and align-items
, you can add the older flexbox syntax as well:
对于跨浏览器的兼容性display: flex
和align-items
,你可以添加上了年纪Flexbox的语法,以及:
display: -webkit-box;
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: flex;
-webkit-flex-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;