想要居中 div 里面有 ion-label,但是后面的宽度是 100%

Want to center div with ion-label inside, but latter width is 100%

我正在做一个 Ionic 3 应用程序,但我 运行 在设计它的样式时遇到了问题。具体HTML代码是这样的:

<div class="use-conditions">
    <ion-checkbox class="checkbox" formControlName="acceptUseConditions"></ion-checkbox>
    <ion-label text-wrap class="checkbox-label">Want to center this text and the checkbox</ion-label>
</div>
<button class="submit-button" ion-button round type="submit">ENTER</button>

默认情况下,"use-conditions" div 宽度是这样的:

水平填充所有space(与内部ion-label宽度相同)。而且,如果我尝试将此 CSS 应用于 "use-conditions" div:

.use-conditions {
    margin-left: auto;
    margin-right: auto;
    width: 50%
}

它暂时居中(好!):

但是,如果我水平展开 window,它就会失去居中位置:

所以,我认为将宽度设置为 50% 并不好。实现此目标的正确方法是什么?

您可以通过使 use-conditions div inline-block 和它的父 text-align:center

居中

body {
  text-align: center;
}

.use-conditions {
  display: inline-block;
}
<div class="use-conditions">
  <ion-checkbox class="checkbox" formControlName="acceptUseConditions"></ion-checkbox>
  <ion-label text-wrap class="checkbox-label">Want to center this text and the checkbox</ion-label>
</div><br>
<button class="submit-button" ion-button round type="submit">ENTER</button>

或者您可以在使用条件中添加文本居中对齐 div

您可以使用响应式弹性框。

摆脱 margin-auto 和 width: 50%,然后将按钮和 .use-conditions 包裹在 div 中并赋予这些样式。

.wrapper {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
}

这里有一个 fiddle 可以更好地说明如何在这些情况下使用 flex box。 https://jsfiddle.net/q8pyjsvn/42/

这里是让您开始使用 flex box 的好地方。 https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox