父 div 中的中心图像元素 [英] Center image element in parent div

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

问题描述

如何将父 div 中的图像元素设置为居中?我想这样做,以便图像的中间始终位于他父母的中心.此外,我希望图像始终具有 100% 的高度(注意:我不想拉伸图像宽度).

参见此处的示例:http://jsfiddle.net/Ex5ax/5/

<img src='featured.jpg'/>

CSS:

.box { 高度:100%;宽度:450px;边框:2px纯红色;背景:绿色;溢出:隐藏;}.box img { 高度:100%;宽度:自动;文本对齐:居中;}

解决方案

添加 text-align: center; CSS 声明到父 .box 而不是子<代码>.box img.

.box {高度:100%;宽度:450px;边框:2px纯红色;背景:绿色;溢出:隐藏;文本对齐:居中;/* 居中对齐所有行内元素 */}

这是小提琴.

更新

图片下方好像还有一个5px的空隙,属于行高保留字符.要从 <img> 之类的内联元素中删除它,您可以使用 vertical-align: bottom:

.box img {高度:100%;宽度:自动;垂直对齐:底部;/* <-- 修复垂直间隙 */}

JSFiddle 演示 #2

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).

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; }

解决方案

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 */
}

Here is the Fiddle.

Update

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 */
}

JSFiddle Demo #2

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

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