skip to Main Content

enter image description here

My task is to make the background of the parent element darkened, and the child element should be without darkening, while it should shrink when resized. How to do it better I tried a bunch of options it doesn’t work out properly when resizing

2

Answers


  1. An alternative approach to achieve the desired result. Instead of using transform: scale() on the child element, we can achieve the desired result by using the CSS calc() function along with vw units for width and height. This will ensure that the child element always remains in proportion to the parent element when resized.
    
    html 
    
      <div class="parent">
         <div class="child">
            <!-- Content goes here -->
        </div>
      </div>
    
    css
    
    .parent {
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100vw;
        height: 100vh;
    }
    
    .child {
        background-color: #ffffff;
        padding: 20px;
        width: calc(100% - 40px);
        height: calc(100% - 40px);
        box-sizing: border-box;
    }
    
    In this solution, we use the CSS calc() function along with vw units for width and height. The calc() function calculates the value of the CSS expression inside it. Here, we subtract 40px from 100% to maintain the desired padding. The box-sizing: border-box; property ensures that the padding is included in the element's total width and height.
    
    Login or Signup to reply.
  2. <!DOCTYPE html>
     <html lang="en">
      <head>
       <meta charset="UTF-8" />
       <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <style>
      * {
        box-sizing: border-box;
      }
      html {
        height: 100%;
      }
    
      body {
        margin: 0;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    
      .parent {
        position: relative;
        width: 100%;
        height: 100vh;
        background-color: rgba(0, 0, 0, 0.7);
        overflow: hidden;
      }
    
      .child {
        width: 50%;
        height: 50%;
        background: white;
        position: absolute;
        top: 25%;
        left: 25%;
        bottom: 25%;
        right: 25%;
      }
       </style>
      </head>
     <body>
        <div class="parent">
        <div class="child"></div>
      </div>
     </body>
     </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search