CSS display: flex, align-center and button with checkboxes

泄露秘密 提交于 2019-12-25 13:06:26

问题


There is a flex box with buttons and a label inside. Apparently align-items property does not align buttons. How can I achieve that?

https://jsfiddle.net/elaman/4uyggo7s/

<div class="wrapper">
    <div>
        <button>Test</button>
    </div>
    <div>
        <input type="checkbox" id="test" />
        <label for="test">Test</label>
    </div>
    <div>
        <button>Test</button>
    </div>
    <div>
        <button>Test</button>
    </div>
</div>

CSS

.wrapper {
    display: flex;
}
.wrapper > * {
    align-items: baseline;
}
.wrapper > :first-child {
    flex: 1 0 auto;
}
.wrapper button {
    padding: 10px;
}

Update: I'm searching the way to vertically align label, checkbox and button to the single baseline.


回答1:


The align-items property applies to flex containers, not flex items.

So you should apply it to .wrapper instead of .wrapper > *:

.wrapper {
  align-items: baseline; /* Align the baselines of the flex items */
}

.wrapper {
  display: flex;
  align-items: baseline;
}
.wrapper > :first-child {
  flex: 1 0 auto;
}
.wrapper button {
  padding: 10px;
}
<div class="wrapper">
  <div>
    <button>Test</button>
  </div>
  <div>
    <input type="checkbox" id="test" />
    <label for="test">Test</label>
  </div>
  <div>
    <button>Test</button>
  </div>
  <div>
    <button>Test</button>
  </div>
</div>

Moreover, I suggest simplifying the markup, removing unnecessary inner wrappers:

.wrapper {
  display: flex;         /* Magic begins */
  align-items: baseline; /* Align the baselines of the flex items */
}
.wrapper > :first-child {
  margin-right: auto;    /* Push following flex items to the right */
}
.wrapper button {
  padding: 10px;
}
<div class="wrapper">
  <button>Test</button>
  <input type="checkbox" id="test" />
  <label for="test">Test</label>
  <button>Test</button>
  <button>Test</button>
</div>


来源:https://stackoverflow.com/questions/30741025/css-display-flex-align-center-and-button-with-checkboxes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!