-5

Desired effect: background image with 100% height and horizontally starts at 50% of the element. (The background ends before the right end of the element, or overflows hidden at the right edge of the element depending on the image / element size ratio)

MDN "A <length> or <percentage>. This specifies the X coordinate relative to the left edge, with the Y coordinate set to 50%."

So I tried to set background-position:50%; but oddly this centers the background image horizontally. Background pivot is set to center when using % values? Even MDN example shows this behaviour.

I know there is a "hack" with :after pseudo element to achieve this effect, I just wonder is this possible with "background" css properties?

jo_va
  • 13,504
  • 3
  • 23
  • 47
  • "100% height background starting at **50% horizontally**" "So tried to set background-position:50%; but oddly this **centers the background image horizontally.**" So it does what you want but you find it odd 50% is the same as center? – Raymond Nijland Feb 09 '19 at 12:49
  • @RaymondNijland No, the desired effect is: background's **left edge** to be at 50% of the element, while it stays at 100% height. https://developer.mozilla.org/en-US/docs/Web/CSS/background-position If you set here 50% 50% , you will see the background is full centered. – d.gabriel.asa Feb 11 '19 at 08:38

1 Answers1

0

Like you already noticed and as I explained here background-position with percentage won't behave like you may think.

An idea to achieve this is to consider adjusting background-origin like below:

.box {
  padding-left:50%;
  height:300px;
  border:1px solid;
  background:url(https://picsum.photos/200/200?image=1069) left/100% auto no-repeat;
  background-origin:content-box;
}
<div class="box">

</div>

the trick is to have the padding covering half the width and we start placing the background inside the content-box

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • This pretty close, despite it forces to use add position: relative on the element and position: absolute on it's content. – d.gabriel.asa Feb 11 '19 at 08:43
  • @d.gabriel.asa it will depend on the content but as you already found, you can consider pseudo element so it may probably be better than this. I simply tried to find a way with pure background even if it's not really something we should use in production. – Temani Afif Feb 11 '19 at 08:45