Home >Web Front-end >CSS Tutorial >How Can I Prevent Flex Items from Rendering Side-by-Side Instead of Stacking Vertically?

How Can I Prevent Flex Items from Rendering Side-by-Side Instead of Stacking Vertically?

Susan Sarandon
Susan SarandonOriginal
2024-12-07 17:35:13471browse

How Can I Prevent Flex Items from Rendering Side-by-Side Instead of Stacking Vertically?

Preventing Flex Items from Rendering Side-by-Side

When using flexbox, we often encounter situations where we want to center items in a block, but with each item occupying its own row. Unfortunately, flexbox sometimes moves items aside when we want them positioned below each other.

Consider the following HTML structure, where an orange square and a text element are placed inside a container using flexbox with justify-content: center and align-items: center:

<div class="container">
  <div class="inner">
    <div class="square"></div>
    <p>some text</p>
  </div>
</div>

And the associated CSS:

.container {
  height: 200px;
  width: 200px;
  background: cornflowerblue;
  position: relative;
}

.inner {
  height: 100%;
  position: absolute;
  left: 0;
  width: 100%;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.square {
  width: 30px;
  height: 30px;
  background: tomato;
  display: block;
}

Upon applying flexbox, the orange square, instead of being positioned above the text, ends up to the side. To rectify this, we need to modify the inner container's flex-direction property:

.inner {
  ...
  flex-direction: column;
}

Setting flex-direction: column instructs the flexbox to display its children vertically, one below the other, instead of in a row. This behavior aligns with our requirement, placing the orange square above the text.

The above is the detailed content of How Can I Prevent Flex Items from Rendering Side-by-Side Instead of Stacking Vertically?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn