Related Articles

Related Articles

Fluid width with equally spaced div using CSS
  • Difficulty Level : Expert
  • Last Updated : 26 Nov, 2020

There are two methods to create equally spaced “div” element using CSS.

Method 1: Using Flexbox technique in CSS

Approach: We can make a container and then set the display property to flex. It creates a Flexbox. Now we can apply flexbox properties to the items of the container. So, we will set justify-content property to space-between to create equal sized “div” elements.

Syntax:

.container {
    display: flex;
    justify-content: space-between;
}

Example 1: The following code illustrates the above concept.



HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
          
    <style>
        #container {
            width: 98vw;
            height: 100vh;
            border: 2px solid black;
            /*Making the container a flexbox*/
            display: flex;
            /*Making equal spaced divs*/
            justify-content: space-between;
            background-color: black;
        }
  
        .box {
            width: 20%;
            height: 25%;
            background-color: red;
            color: white;
            font-size: 2rem;
            border: 4px solid white;
        }
    </style>
</head>
  
<body>
    <div id="container">
        <div class="box">Box1</div>
        <div class="box">Box2</div>
        <div class="box">Box3</div>
        <div class="box">Box4</div>
    </div>
</body>
  
</html>

chevron_right


Output:

Equally Spaced div elements using flex property

Method2: Using grid property in CSS

Approach: First we set the display of the container as grid. Then use the gap property of CSS to create equal spaced “div” elements.

Syntax:

.container {
    display: grid;
    gap: 1rem;
}

Example 2: The following code illustrates the above concept.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
  
    <style>
        #container {
          
            /* Using the grid property */
            display: grid;
            grid-template-columns: 1fr 1fr 1fr 1fr;
  
            /* Making equal spaced divs */
            gap: 1rem;
        }
  
        .box {
            border: 4px solid black;
            background-color: red;
            height: 30vh;
        }
    </style>
</head>
  
<body>
    <div id="container">
        <div class="box">Box1</div>
        <div class="box">Box2</div>
        <div class="box">Box3</div>
        <div class="box">Box4</div>
    </div>
</body>
  
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :