将图片居中在一个太小的图片中? [英] Center an image in a div too small for it?

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

问题描述

所以我有一个div在我的身体是一个百分比的宽度,并在里面的内联样式的div如下:

So I have a div in my body that's a percentage width, and inside that a div with inline style as follows:

text-align: center; margin-left: -15px; margin-right: -15px; overflow: hidden;

正如你所看到的,我有 text-align:center; code> on,如果图像对于 div 足够小,那么会使图像居中。但是在我的1280x800屏幕上,百分比宽度 div 肯定不够大。

As you can see, I have text-align: center; on, which would, if the image was small enough for the div, center the image. But the percentage width div is definitely not going to be big enough on my 1280x800 screen.

负边距以克服它上面的一些填充 div overflow:hidden 使事情看起来像我想要的,而不是凌乱。所以,它的工作方式像我想要的,像 onenaught.com 的标题图片。它会变得更加明显,因为你使浏览器更宽,但不能从两侧扩展,因为它不居中。

The negative margins are to overcome some padding on it's parent div. The overflow:hidden makes things look like I want, not messy. So, it's kind of working like I want it, like the header image at onenaught.com. It will become more visible on the right as you make the browser wider, but not expand from both sides, because it's not centered.

所以,我想知道是否有任何方式以使图像居中。知道吗?

So, I wonder if there's any way to center the image. Know of any?

编辑:这里

推荐答案

一个选择是使用 left:50%,然后在图像上使用负余量 - 等于图像宽度的一半。当然,这需要包含 div 将其定位设置为relative或absolute,以便为要绝对定位的图像提供正确的容器类型。

One option would be to absolutely position the image with left: 50% and then use a negative margin-left on the image equal to half of the image's width. Of course, this requires the containing div to have its positioning set to relative or absolute in order to provide the proper container type for the image to be absolutely positioned within.

另一个选项(可能更好)不是使用图片标签,而是将图片设置为父div的背景,并使用背景定位CSS属性将其居中。这不仅确保它的中心没有强制绝对定位,但它也自动作物溢出,所以溢出属性不是必需的。

The other option (and probably better) is instead of using an image tag, just set the image as the background for the parent div, and use the background positioning CSS attributes to center it. Not only does this make sure it's centered without forcing absolute positioning, but it also automatically crops overflow, so the overflow attribute isn't necessary.

这篇关于将图片居中在一个太小的图片中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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