Search code examples
htmlcssrowcol

Changing widths of element according to number of elements in parent element


I am writing a HTML page consists of rows and columns in DIV elements.

Sometimes a row may only contain 1 column, some 2, and some 3, and I want to change the width of each column depending on how many columns there are in a row.

Here is my HTML examples here:

<!-- 1 column -->
<div class="row">
  <!-- Column will be 100% -->
  <div class="col"></div>
</div>

<!-- 2 columns -->
<div class="row">
  <!-- Column will be 25% -->
  <div class="col"></div>

  <!-- Column will be 75% -->
  <div class="col"></div>
</div>

<!-- 3 columns -->
<div class="row">
  <!-- Column will be 25% -->
  <div class="col"></div>

  <!-- Column will be 50% -->
  <div class="col"></div>

  <!-- Column will be 25% -->
  <div class="col"></div>
</div>

I am unsure how I would code this in CSS however and was hoping somebody could point me in the right direction?

Peter


Solution

  • The easiest way is to to add another class to the row divs, designating how many divs it contains:

    <!-- 3 columns -->
    <div class="row col3">
      <!-- Column will be 25% -->
      <div class="col"></div>
    
      <!-- Column will be 50% -->
      <div class="col"></div>
    
      <!-- Column will be 25% -->
      <div class="col"></div>
    </div>
    

    and add styles accordingly:

    .col3 div {
       width: 33%;
    }
    

    This would give all div-elements in a div with class col3 33% width.