Thomas Stock
Thomas Stock

Reputation: 11266

center only item in a flex container

How can I center .search as the only item in a .flex container?

body{
    background-color:green;
}

.bar{
    background-color:yellow;
    display:flex;
    justify-content: space-between;
}

.search{
    background-color:red;
    align-self: center;
}
<body>
    <div class="bar">
        <div class="search">
            <input type="search" placeholder="Search" />
            <button id="cancel">Cancel</button>
        </div>
    </div>
</body>

It works when I add more items:

body {
    background-color:green;
}
.bar {
    background-color:yellow;
    display:flex;
    justify-content: space-between;
}
.search {
    background-color:red;
    align-self: center;
}
<body>
    <div class="bar">
        <div class="menu"><a href="#">menu</a>

        </div>
        <div class="search">
            <input type="search" placeholder="Search" />
            <button id="cancel">Cancel</button>
        </div>
        <div class="closebar"><a href="#">close</a>

        </div>
    </div>
</body>

But why does it work when there are other items?

Upvotes: 1

Views: 63

Answers (2)

Anonymous
Anonymous

Reputation: 10216

Set justify-content: center; instead of justify-content: space-between;

body{
    background-color:green;
}

.bar{
    background-color:yellow;
    display:flex;
    justify-content: center;
}

.search{
    background-color:red;
    align-self: center;
}
<body>
    <div class="bar">
        <div class="search">
            <input type="search" placeholder="Search" />
            <button id="cancel">Cancel</button>
        </div>
    </div>
</body>

For More Info:

Mozilla MDN - justify-content

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123387

It works if you specify the auto value for left and right margin to .search element:

body {
    background-color:green;
}
.bar {
    background-color:yellow;
    display:flex;
    justify-content: space-between;
}
.search {
    background-color:red;
    align-self: center;
    margin: 0 auto;
}
<body>
    <div class="bar">

        <div class="search">
            <input type="search" placeholder="Search" />
            <button id="cancel">Cancel</button>
        </div>

        </div>
    </div>
</body>

Upvotes: 3

Related Questions