仅限中心容器中的项目

时间:2014-09-18 07:28:26

标签: html css flexbox

如何将.search作为.flex容器中唯一的项目?



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>
&#13;
&#13;
&#13;

当我添加更多项目时,它会起作用:

&#13;
&#13;
body {
    background-color:green;
}
.bar {
    background-color:yellow;
    display:flex;
    justify-content: space-between;
}
.search {
    background-color:red;
    align-self: center;
}
&#13;
<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>
&#13;
&#13;
&#13;

但是为什么还有其他项目时呢?

2 个答案:

答案 0 :(得分:3)

如果您为auto元素的左右边距指定.search值,则此方法有效:

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>

答案 1 :(得分:1)

设置justify-content: center;而不是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>

更多信息:

  

Mozilla MDN - justify-content