CSS3 background-position issue with Safari only

2019-02-08 16:57发布

问题:

The following code renders well in IE9, FireFox, Chrome, but not in Safari:

.search-choice
{
  position: relative;
  background-clip : padding-box;
  background-image: url('../Design/icon_chosen_close.gif');
  background-repeat: no-repeat;
  background-position: top 6px right 6px;
}

<ul class="chzn-choices">
    <li class="search-choice" id="selLVB_chzn_c_0">
        <span>multi1</span><a href=# class="search-choice-close" rel="0"></a>
    </li>
</ul>

Safari doesn't seem to take into account the background-position. I have tried a number of variants (like background-position-x: right 6px), but nothing seems to work. I just can't offset the background image in Safari starting from the top right corner.

Any ideas? Thanks a lot for your time!

回答1:

Found out that Safari marks the following line as invalid and the background image won't be displayed:

background-position: top 15px right 0px;

But when I type only:

background-position: top right;

Safari generates the following by itself:

background-position-x: 100%;
background-position-y: 0%;

Found then out that Firefox completely ignores:

background-position-x: 100%;
background-position-y: 0%;

So finally I did it with:

background: url(../images/image.png) no-repeat;
background-position: top 15px right 0px;
background-position-x: 120%;
background-position-y: 0%;

Whilst Safari ignores the second line, Firefox ignores the last two lines.

This tweak seems to work in older Internet Explorers, too. Tested in IE8.



回答2:

There is a bug open in Safari's implementation around the long-hand syntax of background-position: https://bugs.webkit.org/show_bug.cgi?id=37514

My fix for this was to use background-position: top right; in combination with right padding and background-origin: content-box;

It may also be useful in some scenarios to use a pseudo element instead of a background image, and just position that as you would the background.



回答3:

If you can set right position from right and top only, you can still do it old school.

background:url("../images/") no-repeat Xpx Ypx;

Where X marks width from left, and Y height from top.



回答4:

I had a similar issue when giving an <a>-tag a background-image. To give it display: inline-block; solved the problem for me.



回答5:

Best way is to use:

background-size: auto;