center< IMG />在< DIV>与CSS [英] center <IMG/> inside a <DIV> with CSS

查看:130
本文介绍了center< IMG />在< DIV>与CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图片放在div中心。 div的宽度固定为300像素。图像宽度仅在运行时已知。它通常大于300像素,因此图像应该居中并且向右和向左切割。在这种情况下,margin 0 auto不起作用。

I want to center image inside a div. The div has fixed width 300px. The image width is known only at runtime. It usually is bigger then 300px, so image should be centered and cut right and left. margin 0 auto does not work in this case.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">

div{width:300px;border:1px solid red; overflow:hidden}

img{
/* NOTE!!!!
margin:auto; doesn't work when image width is bigger than div width
image width is known only at runtime!!!
*/
}
</style>
</head>

<body>
<div>
    <img src="" />
</div>
</body>
</html>

感谢任何css想法

UPD 此有趣的任务遵循 这里

UPD This interesting task is followed here

推荐答案

如果您在图像周围包围另一个元素,您可以使其工作:

You can make it work if you wrap another element around the image:

<div class="outer">
    <div class="inner"><img src="" alt="" /></div>
</div>

和以下CSS:

.outer {
    width: 300px;
    border: 1px solid red;
    overflow: hidden;
    *position: relative;
}
.inner {
    float: left;
    position: relative;
    left: 50%;
}
img {
    display: block;
    position: relative;
    left: -50%;
}

position:relative .outer 上标有 * ,因此仅适用于IE6 / 7。你可以把它移动到一个有条件的IE样式表,如果这是你喜欢的,或删除 * 。它需要避免现在相对定位的孩子溢出。

The position: relative on the .outer is marked with * so it only applies to IE6/7. You could move it to a conditional IE stylesheet if that's what you prefer, or remove the * altogether. It's needed to avoid the now relatively positioned children from overflowing.

这篇关于center&lt; IMG /&gt;在&lt; DIV&gt;与CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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