为什么绝对定位的图像仍占用空间?

时间:2014-03-08 11:09:48

标签: css

我试图以间接的方式将图像作为背景图像:通过制作绝对定位的图像。这张图片非常大。但是,我注意到图像仍然扩展了我的网页范围。这是为什么?它绝对定位,所以它不应该这样做,对吗?

以下是我的意思:http://jsfiddle.net/xeV6t/

佛罗里达的巨大印章绝对定位并以屏幕为中心

img {
    width: 1000px;
    height: 1000px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -500px;
    margin-left: -500px;
}

但它仍占用空间并扩展网页,如强制用户滚动的方式所示。我不希望这种扩张发生。我如何让它消失?

我尝试使用overflow:hidden,但这并没有达到我想要的效果 - 我仍然希望用户在页面很长的情况下向上和向下滚动。

2 个答案:

答案 0 :(得分:1)

body
{
overflow-x:hidden;
}

它会隐藏水平滚动条。

答案 1 :(得分:1)

您的图片仍然是一个DOM对象,占用空间,绝对定位或不是


background-size:cover

你应该看看this

http://jsfiddle.net/QhNRH/

html { 
  background: url(images/bg.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

如果您将图像作为绝对定位div的背景图像,它应该可以满足您的需求:

img {
    width: 1000px;
    height: 1000px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -500px;
    margin-left: -500px;
    background: url(images/your_image.png) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}