如何在具有多个项目的Flexbox中居中放置单个项目?

时间:2018-07-06 00:03:37

标签: css reactjs flexbox

当前,我的.css代码为:

.form-wrapper {
  display: flex;
  justify-content: space-between
}

.testingForm {
  max-width: 320px;

}

.centerThis {
  align-self: center;
}

我的.js代码是:

<div className="form-wrapper">
  <div className="testingForm">
    <FormGroup
      controlId="stuff"
      bsSize="large"
    >
      <ControlLabel>Stuff</ControlLabel>
      <FormControl
      />
    </FormGroup>
  </div>
  <div className="centerThis">
    <h1>Stuff here</h1>
  </div>
</div>

如何将“ centerThis”类名居中,并将“ testingForm”类名保留在当前位置?我似乎无法分离“ testingForm”和“ centerThis”。我已经尝试过align-content和其他各种方法来解决这个问题,但是没有运气。

如果有帮助,运行开发服务器后检查器的html输出将显示:

<div class="form-wrapper"><div class="testingForm"><div class="form-group form-group-lg"><label for="accountID" class="control-label">Stuff</label><input id="ID" class="form-control" value=""></div></div><h1>AWS</h1></div>

1 个答案:

答案 0 :(得分:0)

将flex一级div设置为width: 100%;

.form-wrapper > div {
    width: 100%;
}

然后,.centerThis如果只是文本和/或图像,则可以text-align:center,也可以将其设置为display:flexjustify-content:center

.centerThis {
    text-align: center;
}

.centerThis {
    display: flex;
    justify-content: center;
}

.form-wrapper {
  display: flex;
}
.form-wrapper > div{
  width: 100%;
}

.testingForm {
  max-width: 320px;

}

.centerThis {
  text-align: center;
}
<div class="form-wrapper">
  <div class="testingForm">
    <FormGroup
      controlId="stuff"
      bsSize="large"
    >
      <ControlLabel>Stuff</ControlLabel>
      <FormControl
      />
    </FormGroup>
  </div>
  <div class="centerThis">
    <h1>Stuff here</h1>
  </div>
</div>

已编辑

基于您的输出HTML ...

将flex一级元素设置为width: 100%;

.form-wrapper > div,
.form-wrapper > h1 {
    width: 100%;
}

然后h1将其设置为display:flexjustify-content:centeralign-items: center

.form-wrapper h1 {
    display: flex;
    justify-content: center;
    align-items: center;

}

body, html {
  height: 100%;
  margin: 0; /* Reset browser default */
}
.form-wrapper {
  display: flex;
  height: 100%;
}
.form-wrapper > div,
.form-wrapper > h1{
  width: 100%;
}

.testingForm {
  max-width: 320px;

}

.form-wrapper h1 {
    display: flex;
    justify-content: center;
    align-items: center;
    
}
<div class="form-wrapper">
  <div class="testingForm">
    <div class="form-group form-group-lg">
      <label for="accountID" class="control-label">Stuff</label>
      <input id="ID" class="form-control" value="">
    </div>
  </div>
  <h1>AWS</h1>
</div>