1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

background-size > 100% だと background-position: n% が逆向きになる

Last updated at Posted at 2023-01-08

※ 解決しました
詳しくはコメント欄をご覧ください。
@degudegu2510 さま、ありがとうございました!!

確認環境

Firefox 108.0.2
Google Chrome 108.0.5359.125

目的

background-image を設定したうえで background-position-x: 30% というように % 指定でずらしたい。
https://developer.mozilla.org/ja/docs/Web/CSS/background-image
https://developer.mozilla.org/ja/docs/Web/CSS/background-position-x

親要素が例えば 300px だった場合、30% 指定は 90px を指定したのと同じことになるはず。
https://developer.mozilla.org/ja/docs/Web/CSS/percentage

しかし…

なぜか、指定した background-image の大きさが親要素の大きさを超えると、background-position-x: 30% の指定が右側ではなく、左側にずれてしまします。
また、 background-image の大きさがちょうど親要素と同じくらいのサイズの場合、全くずれなくなります。

例:%指定だと意図した通りにpositionがずれない

  • %指定の場合、backfround-image が…
    • 親要素と同じ大きさ:全くずれない
    • 親要素より大きい:逆側にずれる
    • 親要素より小さい:想定した挙動

background-position-x: 30% のはずの div.big.right が左にずれ、
background-position-x: -30%div.big.left が左にずれています。

See the Pen background-% by manjuu-eater (@manjuu-eater) on CodePen.

おかしい…。
MDNの background 関連をあちこち見ましたが、なぜこうなったのかはわかりませんでした。

例2:px指定だと意図した通りになる

ちゃんと right が右にずれてくれています。

See the Pen background-px by manjuu-eater (@manjuu-eater) on CodePen.

解決策

わかりません(絶望)
⇒ 超絶親切な方がコメント欄に情報をくださいました。
(後で追記します)

手計算で親要素のpxを計算して、そこからcalcでもしてpxで指定するしかないんでしょうか…。

なにかわかり次第追記します。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?