Search code examples
cssmedia-querieswidthpaddinginline

How to make inline-size include padding for container queries?


My header element has padding, which the container query doesn't include in calculating the width of the element. Therefore, when the full width of the element is 800px, the container query thinks the width is actually 800px - 2rem * 2 (both sides of the container) = 734px;

My question is, how do I include the padding within the container queries width, so that when the header element's full width is 800, the container query is triggered? (instead of triggering it at 734px).

<header>
    <h1>hello world</h1>
</header>
header {
    container-type: inline-size;

    max-width: 1180px;
    min-height: 500px;
    font-size: 3rem;
    margin: 0 auto;

 padding: 2rem;
}
@container (width < 800px) {
    header {
        font-size: 2rem;
 }
}

I have tried to use box-sizing: border-box so that the padding is included in the width, but that didn't help.

I could decrease the width to 734px, but than other containers which do not include padding will also trigger at 734px;


Solution

  • Container queries enable you to apply styles to an element based on the size of the element's container. In other words, you can apply styles to the descendent elements of the container, not the container itself (as you are trying to do.)

    This doesn't work because header is the container:

    @container (width < 800px) {
      header {
        font-size: 2rem;
      }
    }
    

    In this example, the styles are applied to the h1 as header is given width: 799px. Also, keep in mind that the default h1 font size of 2em overrules the font-size declaration for header before the container query is considered.

    header {
      width: 799px;
      container-type: inline-size;
      max-width: 1180px;
      min-height: 500px;
      font-size: 3rem;
      margin: 0 auto;
      padding: 2rem;
    }
    @container (width < 800px) {
      header { /* invalid, has no effect */
        font-size: 2rem;
        color: orange;
      }
      h1 {
        font-size: 2rem;
        color: firebrick;
      }
    }
    <header>
      <h1>hello world</h1>
      <p>hello world</p>
    </header>


    You could make body the container to determine the width.

    body {
      width: 799px;
      container-type: inline-size;
    }
    
    header {
      max-width: 1180px;
      min-height: 500px;
      font-size: 3rem;
      margin: 0 auto;
      padding: 2rem;
    }
    @container (width < 800px) {
      header {
        font-size: 2rem;
        color: orange;
      }
      h1 {
        font-size: 2rem;
        color: firebrick;
      }
    }
    <header>
      <h1>hello world</h1>
      <p>hello world</p>
    </header>