skip to Main Content

How do I set the one background for all inner-blocks

<div class="outer-block">
   <div class="inner-block"></div>
   <div class="inner-block"></div>
   <div class="inner-block"></div>
</div>

To make it look like in the photo

In the example with the photo, I used the property:
background-attachment: fixed;

.outer-block {
  position: relative;
  overflow: hidden;
}

.inner-block {
  background-image: url('./dsa.jpg');
  width: 100%;
  height: 200px;
  margin: 10px;
  background-size: contain;
  background-attachment: fixed;
  background-repeat: no-repeat;
}

But this implementation has a drawback. When scrolling the page, the image remains fixed relative to the page.
Task: make sure that when scrolling, the internal blocks and the image move synchronously (expected behavior)

2

Answers


  1. Use pseudo element positioned relatively to the container and clipped at child level

    .outer-block {
      position: relative; /* relative on the container */
      width: 300px;
    }
    .inner-block {
      height: 150px;
      clip-path: inset(0); /* clip-path on the child */
      margin: 10px;
    }
    /* your background */
    .inner-block:before {
      content:"";
      position: absolute;
      inset: 0;
      background: url(https://picsum.photos/id/1/200/600) center/cover;
    }
    /**/
    
    body {
      background: lightblue;
    }
    <div class="outer-block">
      <div class="inner-block"></div>
      <div class="inner-block"></div>
      <div class="inner-block"></div>
    </div>
    Login or Signup to reply.
  2. Also…

    body {
      background : #032b52;
      margin     : 20px;
      }
    .img-block {
      background : url('https://picsum.photos/id/42/400/700');
      width      : 400px;
      height     : 700px;
      border     : solid white 10px;
      }
    .img-block > div {
      border       : solid white 5px;
      border-right : none;
      border-left  : none;
      background   : transparent;
      height       : 225px;
      width        : 100%;
      }
    <div class="img-block">
       <div></div>
       <div></div>
       <div></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search