Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

html - Prevent flex items from rendering side to side

I'm using flexbox to center some items in a block, but I want each item inside to be in its own row. For example, I want the orange square to be above the text, but after using flex it's moved it to the side of the text - does anyone know a way around this please?

.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>
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add this style:

.inner {
  flex-direction: column;
}

That tells the flexbox to display its children in rows instead of columns. (I know, weird, right?)

Updated Snippet:

.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;
  flex-direction: column;
}

.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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...