skip to Main Content

Say I have this HTML

<div id="outer">
  <div id="inner">
    <div id="nested">
    </div>
  </div>
</div>

Where

  • all the DIVs are responsive, in that #outer’s width is a percentage of the window width
  • #inner is "always" smaller than #outer

With CSS, is there a way to set the width of #nested so that it’s a percentage of the width of #outer?

2

Answers


  1. You can do so with position: relative and position: absolute

    Both these attributes go hand-in-hand as the absolute element is positioned relative to its closest parent/ancestor. It goes up to the body tag if none are found. By setting position: relative on outer, you make it the closest ancestor, so the width of nested adjusts in relation to that.

    #outer {
      height: 10rem;
      width: 80vw; /* 80% of the screen width */
      background: red;
      position: relative;
    }
    
    #inner {
      height: 10rem;
      width: 80%;
      background: gray;
    }
    
    #nested {
      height: 10rem;
      width: 50%;
      background: black;
      position: absolute;
    }
    <div id="outer">
      <div id="inner">
        <div id="nested">
        </div>
      </div>
    </div>
    Login or Signup to reply.
  2. Take advantages of the CSS FlexBox Layout and the flex property and all of its great features. You can read more about flex on this link. Check my example below using the flex value in the display property. Happy Coding!

    body {
        background-color: #000738;
    }
    #outer {
        width: 80%;
        margin: 0 auto;
        background-color: #ef3340;
        height: 240px;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 90vh;
    }
    
    #inner {
        width: 79%;
        background-color: #04aeec;
        display: flex;
        justify-content: center;
        align-items: center;
      height: 80vh;
    }
    
    #nested {
        width: 77%;
        background-color: #88df80;
        height: 60vh;
    }
    <div id="outer">
       <div id="inner">
          <div id="nested">
          </div>
       </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search