CSS flexbox 垂直/水平居中图像,无需明确定义父高度 [英] CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

查看:19
本文介绍了CSS flexbox 垂直/水平居中图像,无需明确定义父高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

onlydiv 和子 img 元素如下所示如何垂直和水平将 img 元素居中,而 明确不定义父 divheight?

<img alt="不,他将成为一名工程师.src="theknack.png"/>

我对 flexbox 不太熟悉,所以如果 flexbox 本身填满了整个高度,但没有填满任何其他不相关的属性,我就可以了.

解决方案

在没有明确定义 height 的情况下,我确定我需要将 flex 值应用于父级 and 祖父 div 元素...

<div style="display: flex;"><img alt="不,他将成为一名工程师.src="theknack.png" style="margin: auto;"/>

<小时>

如果您使用单个元素(例如,单个 flex 元素中的死中心文本),请使用以下内容:

align-items: center;显示:弹性;对齐内容:居中;

With only the parent div and the child img elements as demonstrated below how do I vertically and horizontally center the img element while explicitly not defining the height of the parent 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.

解决方案

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<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:

align-items: center;
display: flex;
justify-content: center;

这篇关于CSS flexbox 垂直/水平居中图像,无需明确定义父高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆