防止弹性项目左右渲染

我正在使用flexbox将某些项目居中放置在一个块中,但我希望其中的每个项目都位于其自己的行中。例如,我希望橙色方块位于文本上方,但是在使用flex之后,将其移动到了文本的侧面-请问有人知道解决这个问题的方法吗?


.container {

  height: 200px;

  width: 200px;

  background: cornflowerblue;

  position: relative;

}


.inner {

  height: 100%;

  position: absolute;

  left: 0;

  width: 100%;

  top: 0;

  display: -webkit-box;

  display: -moz-box;

  display: -ms-flexbox;

  display: -webkit-flex;

  display: flex;

  align-items: center;

  justify-content: center;

}


.square {

  width: 30px;

  height: 30px;

  background: tomato;

  display: block;

}

<div class="container">

  <div class="inner">

    <div class="square"></div>


    <p>some text</p>

  </div>

</div>


潇潇雨雨
浏览 632回答 3
3回答

BIG阳

添加此样式:.inner {&nbsp; flex-direction: column;}这告诉flexbox在行而不是列中显示其子级。(我知道,很奇怪,对吧?)更新的代码段:.container {&nbsp; height: 200px;&nbsp; width: 200px;&nbsp; background: cornflowerblue;&nbsp; position: relative;}.inner {&nbsp; height: 100%;&nbsp; position: absolute;&nbsp; left: 0;&nbsp; width: 100%;&nbsp; top: 0;&nbsp; display: -webkit-box;&nbsp; display: -moz-box;&nbsp; display: -ms-flexbox;&nbsp; display: -webkit-flex;&nbsp; display: flex;&nbsp; align-items: center;&nbsp; justify-content: center;&nbsp; flex-direction: column;}.square {&nbsp; width: 30px;&nbsp; height: 30px;&nbsp; background: tomato;&nbsp; display: block;}<div class="container">&nbsp; <div class="inner">&nbsp; &nbsp; <div class="square"></div>&nbsp; &nbsp; <p>some text</p>&nbsp; </div></div>

慕田峪4524236

我看到这个问题来自:垂直对齐两个 被标记为重复但实际上不是的弹性项目。BTW赋予2个元素不同的垂直位置,请设置以下属性:.container {&nbsp; display: flex;&nbsp; flex-direction: column;&nbsp; align-items: center;&nbsp; justify-content: space-between;}容器内部只有2个元素,它将在顶部显示第一个元素,在底部显示第二个元素。因此,为了使其中1个垂直居中,需要向容器中添加一个空的伪元素,这样容器内就有3个元素。.container:before {&nbsp; content: "";}html, body {&nbsp; height: 100%;&nbsp; margin: 0;}.container {&nbsp; width: 500px;&nbsp; margin: 0 auto;&nbsp; border: 5px solid orange;&nbsp; height: 100%;&nbsp;&nbsp;&nbsp; /* Flex properties */&nbsp; display: flex;&nbsp; flex-direction: column;&nbsp; align-items: center;&nbsp; justify-content: space-between;}.container:before {&nbsp; content: "";}.item-one {&nbsp; border: 5px solid yellow;}.item-two {&nbsp; border: 5px solid red;}<div class="container">&nbsp; <div class="item-one">Item One</div>&nbsp; <div class="item-two">Item Two</div></div>
打开App,查看更多内容
随时随地看视频慕课网APP