skip to Main Content

I tried to get the container style query working, but found some oddities.
Consider the following code:

html

<div class="parent">
  <div class="child">
    ...
  </div>
</div>

CSS

.parent {
  --test-var: red;
  background-color: grey;
}

@container style(background-color: grey)
/* @container style(--test-var: red) */
{
  .child {
    background-color:red;
  }  
}

The above css rule does not apply the ‘child-style’ eventhough this should work following the MDN documentation about this feature.
Using the query on custom properties (i.e. by using the commented css-query), things work as expected/documented (tested with chrome version 128.0.6613.138, among other things).

Maybe this feature is not ready yet to be used in this way.
But if I missed something, I would love to know.

Thanks in advance!

Added a jsfiddle if someone wants to try this out.

2

Answers


  1. Use container-type on your parent element.

    .parent {
      container-type: inline-size;
    }
    

    This should get it working.

    Login or Signup to reply.
  2. style properties visual ones like background-color, might not have uniform support in container queries across all browsers. this feature is still being developed/fine-tuned

    potential workarounds:

    1. use custom properties to apply styles

      @container style(--test-var: red) {
          .child {
            background-color: red; 
      }}
      
    2. for more complicated style adjustments, you can put in place a temporary JavaScript solution as a fallback:

      const parent = document.querySelector('.parent');
      const child = document.querySelector('.child');
      
      const parentBackgroundColor = window.getComputedStyle(parent).backgroundColor;
      if (parentBackgroundColor === 'rgb(128, 128, 128)') {
        child.style.backgroundColor = 'red';
      }
      
    3. or use the above suggested container-type method with width or size based queries.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search