Q:

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?

A:

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>

