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

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

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

cssflexbox

提问by John

With onlythe parent divand the child imgelements as demonstrated below how do I vertically andhorizontally center the imgelement while explicitly notdefining the heightof the parent div?

只有div和子img元素作为证明下面我怎么垂直水平居中的img元素,同时明确不定义heightdiv

<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 heightI determined I need to apply the flexvalue to the parent andgrandparent divelements...

没有明确定义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 flexelement) 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.

现在浏览器对 Flexbox 的支持相当不错。

For cross-browser compatibility for display: flexand align-items, you can add the older flexbox syntax as well:

对于跨浏览器的兼容性display: flexalign-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;