WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Set Space Between Flex Items Using CSS

Topic: HTML / CSSPrev|Next

Answer: Use CSS justify-content Property

You can simply use the CSS justify-content property with the value space-between to set space between flexbox items. In the following example the flex container has 4 items where each flex item has a width of 20%, and the remaining 20% space is distributed evenly between the flex items.

Let's try out this example to understand how it basically works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Set Distance Between Flexbox Items</title>
<style>
    .flex-container {
        height: 300px;
        border: 1px solid black;
        display: flex;
        justify-content: space-between;
    }
    .item {
        width: 20%;
        background: #b4bac0;
    }
</style>
</head>
<body>
    <div class="flex-container">
        <div class="item">Item 1</div>
        <div class="item">Item 2</div>
        <div class="item">Item 3</div>
        <div class="item">Item 4</div>
    </div>
</body>
</html>

In the above example the space between the flex items may vary depending on the width of the flex container. However, if you want to set a fixed space (e.g. 10px, 20px, etc.) between the flexbox items you can simply utilize the CSS padding and margin property.

In the following example the flexbox items will have a fixed margin around them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Set Fixed Space Between Flex Items</title>
<style>
    .flex-container {
        height: 300px;		
        display: flex;
        border: 1px solid black;
        padding: 10px;
    }
    .item {
        flex: auto;
        background: #b4bac0;
        margin: 10px;
    }
</style>
</head>
<body>
    <div class="flex-container">
        <div class="item">Item 1</div>
        <div class="item">Item 2</div>
        <div class="item">Item 3</div>
        <div class="item">Item 4</div>
    </div>
</body>
</html>

Related FAQ

Here are some more FAQ related to this topic:

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties