【问题标题】:Background size and position alternative for < IE 9< IE 9 的背景大小和位置替代
【发布时间】:2015-01-04 04:33:50
【问题描述】:

我对旧 IE 上的 background 属性有疑问。我有一个动态网站,用户可以在其中创建自己的 Pinterest 之类的帖子,其中包含图像和一些文本。过去,当它将图像适合特定的高度或宽度(没有任何类型的图像裁剪逻辑)时,我发现了类似

.image-wrapper {
  background-image: url('some/url.png');
  background-position: center center;
  background-size: cover;
}

成为最好的方法。

但是对于即将到来的项目,我需要保证它也适用于 IE 8,因为 caniuse.com 说它不适合它,我需要一些建议如何将图像适应特定的高度和宽度知道用户想要上传的图片的比例。

我更喜欢仅使用 CSS 的方式,但如果那不令人满意,我也可以使用 JS/jQuery。

【问题讨论】:

    标签: jquery html css image internet-explorer


    【解决方案1】:

    你引用的是CSS background-position edge offsets,这是一个3到4个项目的语法(假设你想做bottom 4px right 10px从右下角偏移4和10px)。 IE8 确实支持二值语法(又名center center,你引用的那个)。可以看到,从版本 4 开始,它就有了基本的支持(二值语法):https://developer.mozilla.org/en-US/docs/Web/CSS/background-position#Browser_compatibility

    但是,您的背景大小问题并不容易解决。通常使用 IE8 的计算机的分辨率不大于 1320x768,因此请确保您的图像是该尺寸。否则,您可以尝试将您的图像作为第一个元素添加到图像标签中,并为其指定 100% 的最小高度和最小宽度;

    <div id="Container">
        <img src="bg.jpg" class="background" />
    </div>
    
    #Container {
        position: relative;
        overflow: hidden;
        width: 100px;
        height: 100px;
    }
    .background {
        min-width: 100%;
        min-height: 100%;
        height: auto;
        width: auto;
        position: absolute; /* need it for z-index and to make sure content overlaps */
        z-index: -1; /* z-index is supported since IE4 */
    }
    

    更新

    我将overflow: hidden; position: relative; 添加到#Container。此外,如果你沿着这条路线走,一个让现代浏览器的图像居中的好方法是:

    .background:nth-child(n){
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
    }
    

    否则,使用javascript:

    $(this).resize(function(){
        $(".background").each(function(){
            var w = $(this).innerWidth() / 2;
            var h = $(this).innerHeight() / 2;
            $(this).css({
                "left" : "50%",
                "top" : "50%",
                "margin-left" : -w + "px",
                "margin-top" : -h + "px"
            });
        });
    });
    $(this).resize();
    

    【讨论】:

    • 我考虑过使用 &lt;img&gt; 标签代替宽度为 100% 的 min-heightmin-width。但问题是,它会根据图像的纵横比留下空白。
    • 就是这样,如果设置了两个最小值,它应该自动缩放以至少覆盖屏幕。问题是在这种情况下,您实际上无法使用 CSS 将图像居中。我最近使用过它,据我所知,它可以一直运行到 IE7。
    • 它会拉伸,是的,但它会扭曲图像,这当然是我不想要的!
    • 如果您的宽度和高度是自动的,它将不会拉伸。它的最小宽度为 100%,但不是 100%。这意味着如果在高度为 100% 时宽度更大,那么宽度会更大。试试看,效果很好。
    • 添加overflow: hidden; position: relative;,因为位置需要在 div 内(因此 div 需要声明位置)并且我们不希望背景在 div 之外。我也会修改我的帖子来做到这一点。
    猜你喜欢
    • 2013-11-04
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    相关资源
    最近更新 更多