CSS Div width percentage and padding without breaking layout

前端 未结 3 513
忘掉有多难
忘掉有多难 2020-12-07 15:54

There may be a simple fix for this, but it has troubled me for ages now...

Let me explain the situation. I have a div with the ID \'container\' that holds all the

3条回答
  •  粉色の甜心
    2020-12-07 16:28

    You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.

    An example:

    width: calc((100%) - (32px))
    

    Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.

    .outer {
      width: 200px;
      height: 120px;
      background-color: black;
    }
    
    .inner {
      height: 40px;
      top: 30px;
      position: relative;
      padding: 16px;
      background-color: teal;
    }
    
    #inner-1 {
      width: 100%;
    }
    
    #inner-2 {
      width: calc((100%) - (32px));
    }
    width of 100%


    width of 100% - 16px

提交回复
热议问题