5

次のように、背景画像に負の左位置を設定できることを知っています。

#element {
    background: url(image.png) -20px 0 no-repeat;
}

の幅#elementに関係なく、背景画像を の左端の左に 20px 配置します。#element

しかし、固定幅を指定せずに(そして、高い正の左値を設定するだけで)負の位置を設定する方法はありますか?#element

4

3 に答える 3

2

あなたがやりたいことは、あなたがやりたい方法では不可能です。

修正は、属性を持つ親 div を作成してからposition: relative;、コンテンツを保持する div の背後にある別の div を z-index することです。

<style>
    #parent {
        position: relative; 
    }
    #background {
        background: url(img.png) top left no-repeat;
        position: absolute;
        top: 0;
        left: -20px;
    }
    #content {
        position: absolute;
        top: 0;
        left: 0;
    }
</style>


<div id="parent">
    <div id="background"></div>
    <div id="content"></div>
于 2013-01-28T20:09:20.547 に答える
1

マークアップを変更せずにこれを実現する別の方法があります。

:after 疑似セレクターを使用すると、実際の css 背景と同じではありませんが、任意のブロックの右側に画像を追加できます

あなたができるように:

#element {
  position: relative;
}
#element:after{
  content: "";
  background: transparent url(image.png) 0 0 no-repeat;
  position: absolute;
  right: -20px;
  top: 0;
  height: 50px /*add height of your image here*/ 
  width: 50px /*add width of your image here*/
  z-index: 1;  
}
#element *{
  position: relative; 
  z-index: 2; /*this makes sure all the "background image" doesn't sit above the elements*/  
}
于 2014-08-01T04:49:36.107 に答える