Search code examples
htmlcssresponsiveness

How can div with be controlled with responsiveness


I have a div with width 364px. There can be one or more same divs inside the container. I want divs width to behave like following.

I want to show maximum 4 div in one row, which i am doing right now. What i want is, if there is one div its width should 100%. if two divs, it should be 50 50 %. If three divs, then width should be 33.3% for each div. If four, then 25% each.

How can i do that?

the container could look like this,

<div class="container">
    <div class="goal"></div>
</div>

or

<div class="container">
    <div class="goal"></div>
    <div class="goal"></div>
    <div class="goal"></div>
</div>

The CSS is the following but i don't know how can implement such rules

.goal {
background: #5A8EAE;
width: 364px;
height: auto;
color: #F4F7F9;
float: left;
margin-right: 20px;
margin-bottom: 20px;
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;

}


Solution

  • Flexbox

    Your div's need to be all equal width so your rule is: flex: 1 0 0 which states:

    flex-grow: 1; /* grow to fill the available space */
    flex-shrink: 0; /* can't shrink, but because the default width is 0, it doesn't need to */
    flex-basis: 0; /* default width */
    

    and set display:flex on .container.

    .goal {
    background: #5A8EAE;
    width: 364px;
    height: auto;
    color: #F4F7F9;
    float: left;
    margin-right: 20px;
    margin-bottom: 20px;
    font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
      flex: 1 0 0;
      -ms-flex: 1 0 0;
      -webkit-flex: 1 0 0;
    }
    
    .container {
      display:flex;
      display:-ms-flex;
      display:-webkit-flex;
    }
    <div class="container">
        <div class="goal">1</div>
        <div class="goal">2</div>
        <div class="goal">3</div>
    </div>
    
    <div class="container">
        <div class="goal">1</div>
        <div class="goal">2</div>
    </div>
    
    <div class="container">
        <div class="goal">1</div>
    </div>