首页 > 解决方案 > CSS flex 居中到父全宽

问题描述

我正在尝试将两个按钮置于其父元素的中心。问题是第一个元素在开头和结尾都有内容,这导致 flex 居中,弄乱了整体的对齐方式。

#container {
  background-color: green;
  width: 100%;
}

#d1 {
  height: 50px;
  display: flex;
}

#d2 {
  background-color: blue;
  width: 50px;
  height: 50px;
}

#d3 {
  background-color: red;
}
<div id="container">
  <div id="d1">
    <p>This is some text</p>
    <input type="button">
    <div id="d2"></div>
  </div>
  <div id="d3">
    <input type="button">
  </div>
</div>

标签: htmlcss

解决方案


您需要justify-content: center;display:flex;父 div 一起使用。

#container {
  background-color: green;
  width: 100%;
  display: flex;
  justify-content: center;
}

#d1 {
  height: 50px;
  display: flex;
}

#d2 {
  background-color: blue;
  width: 50px;
  height: 50px;
  display: flex;
}

#d3 {
  background-color: red;
}
<div id="container">
  <div id="d1">
    <p>This is some text</p>
    <input type="button">
    <div id="d2"></div>
  </div>
  <div id="d3">
    <input type="button">
  </div>
</div>


推荐阅读