我想把图像放在一个div里面. div的宽度为300px.图像宽度仅在运行时才知道.它通常大于300px,所以图像应该是中心的,左右剪切.在这种情况下,margin 0 auto不起作用.
- <!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这个有趣的任务是遵循here
解决方法
如果您在图像周围包装另一个元素,则可以使其起作用:
- <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%;
- }
位置:相对于.outer标有*,所以它只适用于IE6 / 7.你可以把它移动到一个条件的IE样式表,如果这是你喜欢的,或者删除*完全.需要避免现在相对定位的孩子不会溢出.