Search code examples
htmlcssflexboxbackgroundbackground-image

Minimalist Image Slider containing bare minimum HTML & CSS using background-image transition


While trying to set the background with as minimal code as possible HTML code (and put as much as possible into CSS) i'm stuck in this jsfiddle demo.

MAIN QUESTION
Why are the third and fourth slide not the same background size and center origin as the first and second slide? Removing the -image part and using just the shorthand background apparently breaks the background position and centering, despite these rules being explicitely set in the CSS. What have I overlooked?

BONUS QUESTION
The transision has two effects: first a horizontal sliding effect followed by a zoom-in at the end. Is it possible to make both effects to work parallel in stead of one after another? In other words to start the zoom while the slide is horizontally sliding, for a more dynamic smooth transition?

.

style="background-image: url(https://...
Gives the desired zoom/centering result, with background image fitting/centering nicely:
enter image description here

.

style="background: url(https://...
Gives an undesired result, with background image not fitting/centering correctly:
enter image description here


Solution

  • CSS variables are made for this purpose and you can adjust the background-size to have the need transition effect:

    container {
      display: flex;
      margin: auto;
      width: 612px;
      outline: 1px solid black;
      height: 306px;
    }
    
    slide {
      flex: 1;
      background-image: var(--i);
      background-position: center;
      background-size: auto 100%;
      padding: 2px 0 0 2px;
      color: rgba(0, 0, 0, 0.5);
      transition: all .67s ease;
    }
    
    container slide:hover {
      flex: 15;
      background-size: auto 120%;
    }
    <container>
      <slide style="--i: url(https://cdn.dribbble.com/users/729829/screenshots/4185141/galshir-cactus-coffee.png)">1</slide>
      <slide style="--i: url(https://cdn.dribbble.com/users/729829/screenshots/6146136/galshir-tea-biscuit_2x.png)">2</slide>
      <slide style="--i: url(https://cdn.dribbble.com/users/729829/screenshots/4185141/galshir-cactus-coffee.png)">3</slide>
      <slide style="--i: url(https://cdn.dribbble.com/users/729829/screenshots/6146136/galshir-tea-biscuit_2x.png)">4</slide>
    </container>