如何垂直居中图像? [英] How to center image vertically?

查看:136
本文介绍了如何垂直居中图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种垂直居中的方法,类似 text-align center text-align center是有效的,因为你不需要指定父项的宽度或子项的宽度,它会自动将其内容居中。

I am looking for a way to center the image vertically, something that is similar to text-align center. text-align center is kinda efficient since you don't need to specify the width of the parent or the width of the children, it will automatically center its content. Is there any other way to do something like this for positioning image vertically?

推荐答案

您可以通过两种方式进行:

You can do it in 2 ways

方式1(首选),使用 display:table-cell

div {
    display: table-cell;
    height: 100px;
    border: 1px solid #f00;
    vertical-align: middle;
}

演示

方法2,使用 position:absolute; 和 top:50% / code>

Way 2, Using position: absolute; and top: 50% and than deduct 1/2 of the total height of the image using margin-top

div {
    height: 100px;
    border: 1px solid #f00;
    position: relative;
}

div img {
    position: absolute;
    top: 50%;
    margin-top: -24px; /* half of total height of image */
}

演示2

这篇关于如何垂直居中图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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