将图片元素置中父div [英] Center image element in parent div

查看:89
本文介绍了将图片元素置中父div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置图像元素在父div中居中?我想这样做,使图像的中间总是在他的父母的中心。此外,我想让图片始终具有100%的高度(注意:我不想拉伸图片宽度)。

How I can set center an image element inside a parent div? I would like to do this so that the middle of the image is always in the center of his parent. Also I want the image to always have 100% height (note: I don't want to stretch the image width).

请参阅此处查看示例: http://jsfiddle.net/Ex5ax/5/

See here for an example: http://jsfiddle.net/Ex5ax/5/

<div class="box">
  <img src='featured.jpg' />
</div>

CSS:

.box { height: 100%; width: 450px; border: 2px solid red; background: green; overflow: hidden; }
.box img { height: 100%; width: auto; text-align: center; }


推荐答案

添加 text-align :center; c c < 。

Add text-align: center; CSS declaration to the parent .box instead of the children .box img.

.box {
    height: 100%;
    width: 450px;
    border: 2px solid red;
    background: green;
    overflow: hidden;
    text-align: center;  /* align center all inline elements */
}

a href =http://jsfiddle.net/qolami/Ex5ax/10/>小提琴 。

Here is the Fiddle.

图片下面还有一个 5px 空格,它属于行高保留字符。要从< img> 的内联元素中删除它,可以使用 vertical-align:bottom

It seems there's also a 5px gap under the image, It belongs to the line height reserved characters. To remove that from inline elements like <img> you can use vertical-align: bottom:

.box img {
    height: 100%;
    width: auto;
    vertical-align: bottom; /* <-- fix the vertical gap */
}

a href =http://jsfiddle.net/qolami/Ex5ax/25/> JSFiddle Demo#2

JSFiddle Demo #2

这篇关于将图片元素置中父div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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