如何在中心/中间垂直和水平定位图像 [英] How to position image in the center/middle both vertically and horizontally

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

问题描述

<div id="photo_leftPanel" style="float: left; width: 604px; position: relative;">
<img src="bla.jpg">
</div>

如何让图片从这个框的中间开始? (垂直和水平中间)

How can i make the image start from the middle of this box? (middle both vertical and horizontal)

推荐答案

有几种方法可以做到这一点,如果它需要在所有浏览器

There are several ways to do this, and if it needs to work in all browsers (ie7+ and the rest) you need to do different things to make it work in some of the cases.


  1. 使用绝对位置,这只能工作在其他情况下如果你知道图像的大小。
    这里你设置为 position:absolute;左:50%; top:50%;边缘: - <图像的一半高度> 0 0<图片的半宽>

  1. use absolute position, this only works if you know the size of the image. Here you set it to position: absolute; left: 50%; top: 50%; margin: -<half height of image> 0 0 <half width of image>

查看示例:http://jsfiddle.net/JPch8/


  1. 使用 margin:0 auto; text-align:center; line-height / font-size
    这是一个有点更棘手,因为line-height不工作,因为它应该在inline-block元素如图像。
    基本上,您将图像容器的行高设置为与容器高度相同,这将垂直对齐内联元素,但在ie中。您需要设置字体大小,使其工作

  1. use margin: 0 auto;text-align: center; and line-height/font-size. This is a bit more tricky, since line-height doesn't work as it should in ie for inline-block elements like an images. thats where the font-size comes in. Basically, you set the line-height of the image container to the same as the containers height, this will vertically align inline elements, but in ie. you need to set the font-size instead to make it work

请参见示例: http://jsfiddle.net/JPch8/2/

这篇关于如何在中心/中间垂直和水平定位图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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