CSS Container Queries

CSS:


*,

*::before,

*::after {

  box-sizing: border-box;

}



.w-200 {

  max-width: 200px;

}



.w-400 {

  max-width: 400px;

}



.card-container {

  container-type: inline-size;

  width: 100%;

  margin: 0 auto;

  border: 2px dashed grey;

  display: flex;

  flex-wrap: wrap;

}



.card-container--dark {

  container-type: inline-size;

  container-name: container--dark;

}



.card {

  padding: 5px 10px;

  background: linear-gradient(to bottom right, #add8e6, #f0f0f0);

  border-radius: 5px;

  flex: 0 0 100%;

}



@container (inline-size > 300px) {

  .card {

    flex: 0 0 50%;

  }

}



@container (inline-size > 500px) {

  .card {

    flex: 0 0 33.3%;

  }

}



@container container--dark (inline-size > 300px) {

  .card {

    color: white;

    background: linear-gradient(to bottom right, #00008b, #9400d3);

  }

}

HTML:


<h3>1 card per row</h3>

<div class="card-container w-200">

  <div class="card">

    <h4>Title</h4>

    <p>Lorem ipsum dolor sit amet</p>

  </div>



  <div class="card">

    <h4>Another Title</h4>

    <p>Sed do eiusmod tempor incididunt.</p>

  </div>

</div>



<h3>2 cards per row</h3>

<div class="card-container w-400">

  <div class="card">

    <h4>Title</h4>

    <p>Lorem ipsum dolor sit amet</p>

  </div>



  <div class="card">

    <h4>Another Title</h4>

    <p>Sed do eiusmod tempor incididunt.</p>

  </div>

</div>



<h3>3 cards per row</h3>

<div class="card-container">

  <div class="card">

    <h4>Title</h4>

    <p>Lorem ipsum dolor sit amet</p>

  </div>



  <div class="card">

    <h4>Another Title</h4>

    <p>Sed do eiusmod tempor incididunt.</p>

  </div>



  <div class="card">

    <h4>Title</h4>

    <p>Lorem ipsum dolor sit amet</p>

  </div>

</div>



<h3>Example with container-name</h3>



<div class="card-container card-container--dark">

  <div class="card">

    <h4>Title</h4>

    <p>Lorem ipsum dolor sit amet</p>

  </div>



  <div class="card">

    <h4>Another Title</h4>

    <p>Sed do eiusmod tempor incididunt.</p>

  </div>



  <div class="card">

    <h4>Title</h4>

    <p>Lorem ipsum dolor sit amet</p>

  </div>

</div>

Leave a Comment