How can I make a div take the full width of the page when it is inside another div that have 90% width

前端 未结 3 1163
日久生厌
日久生厌 2020-12-12 05:59

how can I make the child take the full width of the page


something
3条回答
  •  一整个雨季
    2020-12-12 06:35

    Consider negative margin.

    .container {
      width: 90%;
      margin: 0 auto;
      padding: 10px 0;
      background: red;
    }
    
    .child {
      height: 50px;
      background: blue;
      margin: 0 calc(-5% / 0.9); 
      /* 
        The container is taking 90% of 100% so we are missing 10%
        we plit this value on both sides (5% + 5%) and since percentage is relative
        to parent so to make the percentage inside .child relative to body
        we divide by the percentage of container
        
        it should be then 5%/0.9 or 5%*1.11
      
      */
    }
    
    body {
      margin: 0;
    }
    something

    With CSS variable you can have something more dynamic:

    .container {
      width: calc(var(--s)*100%);
      margin: 5px auto;
      padding: 10px 0;
      background: red;
    }
    
    .child {
      height: 50px;
      background: blue;
      margin: 0 calc((-50% * (1 - var(--s))) / var(--s)); 
    }
    
    body {
      margin: 0;
    }
    something
    something
    something

    In case the container is not centered simply put all the missing margin on one side:

    .container {
      width: calc(var(--s)*100%);
      margin: 5px 0;
      padding: 10px 0;
      background: red;
    }
    
    .child {
      height: 50px;
      background: blue;
      margin-right:calc((-100% * (1 - var(--s))) / var(--s)); 
    }
    
    body {
      margin: 0;
    }
    something
    something
    something

    PS: the use of vw isn't a good idea because it includes the width of the scroll. So you will have overflow.

    .box {
      height:50px;
      background:red;
      width:100vw;
      border:5px solid green;
      box-sizing:border-box;
    }
    
    body {
     margin:0;
     min-height:200vh;
    }

提交回复
热议问题