Stop flex items from displaying horizontally

I'm having an issue with flexbox where I want each item in a block to be on its own row. Specifically, I want the orange square to be positioned above the text, but it's currently displaying beside it due to using flex. Does anyone have a solution for this?

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

Answer №1

Include the following style:

.inner {
  flex-direction: column;
}

This CSS snippet instructs the flexbox to arrange its child elements in rows rather than columns, which may seem counterintuitive.

Revised Example:

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

Answer №2

By default, when you set a flex container to flex-direction: row, all the child elements will align horizontally.

To change this layout to vertical alignment, you can use flex-direction: column:

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

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

Alternatively, if you want to maintain the horizontal layout but only display one item per row, you can add flex-wrap: wrap to the container and ensure the children have a wide enough width (e.g., width: 100%):

.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;
  flex-wrap: wrap;             /* NEW */
  align-content: center;       /* NEW */
}

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

/* NEW */
p {
  flex: 0 0 100%;            
  text-align: center;
}
<div class="container">
  <div class="inner">
    <div class="square"></div>
    <p>some text</p>
  </div>
</div>


* Remember, only direct children of a flex container participate in the layout. Descendants beyond them do not follow flex behavior.

Answer №3

This question seems to be inspired by a discussion on the topic of Vertically aligning two flex items, which was wrongly marked as a duplicate.

For adjusting the vertical position of two elements differently, you can apply the following properties:

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}

In a container with only two elements, the first one will appear at the top and the second one at the bottom. To vertically center one of them, you need to introduce an empty pseudo-element into the container, making it three elements inside the container.

.container:before {
  content: "";
}

html, body {
  height: 100%;
  margin: 0;
}

.container {
  width: 500px;
  margin: 0 auto;
  border: 5px solid orange;
  height: 100%;
  
  /* Flex properties */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}

.container:before {
  content: "";
}

.item-one {
  border: 5px solid yellow;
}

.item-two {
  border: 5px solid red;
}
<div class="container">
  <div class="item-one">Item One</div>
  <div class="item-two">Item Two</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an HTML button that will execute JavaScript code when clicked

My goal is to create a button that, when clicked, updates the background of another div. These buttons are dynamically generated using PHP from images in a folder. <!DOCTYPE html> <html> <head> <meta charset="UTF-8> <scr ...

Marquee is experiencing issues with incomplete scrolling

Hello everyone, I have been trying to implement a stock market ticker on my website. Initially, I used the marquee tag and it worked fine. Then I tried using simple scroll within the PHP UserCake user management system, but unfortunately, it is not working ...

What is the method for determining the length of a string in JavaScript?

I'm in the process of developing a calculator that can compute the values within a string. To achieve this, I've implemented a Function object, but upon execution of the code, I encounter an issue where I receive a result of 'undefined' ...

Why are static files failing to load on my live Django server when they work fine locally?

My Django website, running version 1.11.29, is failing to load the CSS and JS scripts from the static folder on the live server. Strangely, everything loads properly when I run it locally. Any suggestions? The path to the CSS file appears to be correct, b ...

Load data from SQL into dropdown menu and utilize selections to alter database info

As I continue to develop my skills in programming, I encountered a puzzling issue that I can't seem to figure out. My objective is straightforward: users input data into a form and are then directed to either a results page or back to the form. On the ...

Troubleshooting compatibility issues with Boostap4 and @media queries interfacing

Once the Bootstrap4 CDN is added, the html snippet that was perfectly stacking based on media query no longer maintains this effect. What specific aspect of Bootstrap4 is causing the stacking effect to disappear and how can it be overridden without removin ...

Loading data with Ajax from a remote file using a specific identifier

Can someone lend me a hand with an issue I'm facing? I've set up a small like system here. Within my HTML file, I have various data with unique IDs. Take a look at the code in my remote.html file below: <span id="14">314</span> < ...

When hovering over a div, reveal another div on top of a third div

Imagine two adjacent divs, A on the left and B on the right with some other elements in between. Is it possible to have a third div, C, appear over div A when hovering over div B? I can control the display property using CSS, but I am unsure how to make d ...

Stylishly Select with Bootstrap 4

Currently, I am utilizing Angular 2 with bootstrap 4 and have implemented the following select element: <div class="form-group"> <label class="col-md-4 control-label" for="OptionExample">Choose an option:</label> <div class="c ...

Load link dynamically using the rel attribute

I am trying to implement dynamic content loading using jQuery's .load() function. The links are stored in the .rel attribute of the anchor tags. My setup looks like this: <script> $(document).ready(function(){ $('.sidebar_link').clic ...

An anomaly where a mysterious symbol appears in front of every dollar sign in an HTML document

I have a code written in AngularJS to display the amount in dollars. However, there is an unwanted " Â " character appearing before every " $ " character in the HTML. I am looking for a way to remove this character. Your help is greatly appreciated. Thank ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

What is the best approach to managing a standard form in React without utilizing AJAX?

Trying to access an endpoint https://api.com/signup.ashx is causing CORS issues. I have been instructed to make the API call without using axios or fetch. Here's what I attempted: const handleSubmit = async (event) => { let error = false ...

The element is not positioned correctly due to the absolute positioning

This is my first attempt at creating a jQuery plugin and I have almost got it working correctly. You can view the example here. I've been struggling for days to position an element as desired. The goal is to display some text with an optional downwar ...

Guide on clicking an element in selenium that has an href attribute of "javascript:void(0)" when the element is not attached to the page document

This is the web page HTML structure that caught my attention. <div class="paging"> <a href="javascript:void(0)" id="pcPaging1" class="active">1</a> <a href="javascript:void(0)" id=" ...

Hide Rows or Columns automatically in a Table based on the presence of a specific field in a MySQL Database by implementing it

Currently tackling a challenge in my Django project where I need to hide a table row if a specific entity exists in a column in the database. Using a MYSQL database, I am looking to automatically conceal the row without any user interaction. page.html: &l ...

What is the best way to create a selenium script for this specific html element?

Could somebody provide guidance on clicking the login "button" with Selenium Webdriver? Here is the HTML snippet of the login button. <button class="btn btn-success pull-right " value="submit" type="submit"> Login <i class="m-icon-swapright m-ic ...

Step-by-step guide to dynamically updating array indexes using jQuery and HTML input fields

const list = []; function updateIndex(index) { list.splice(index, 1); console.log(list); var html = ""; html += "<ul id = 'del'>"; for (var i = 0; i < list.length; i++) { html += "<li>" + list[i] + " <button oncl ...

What is the best way to change the size of an SVG image

I have exhausted all the methods I could find on stackoverflow and Google, but my SVG is refusing to resize. Would someone kindly shed some light on why this might be happening? <div> <svg viewBox="32 32 32 32" height="100" width="100"> ...

If the body's height is adjusted, the page will automatically scroll to the top

I'm facing an issue where a button on my HTML page triggers a popup box to open (which covers the background). To prevent the background from scrolling, I am using the following CSS: windowHeight = $(window).height(); $("body").css({ "height": wi ...