Attempting to create a dynamic layout for the objects using media queries and flexbox, however, the results are not as expected

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

.item {
  margin: 10px;
  border: 1px solid lightgray;
  border-radius: 10px;
  overflow: hidden;
  width: 100%;
}

@media screen and (min-width:700px) {
  .item {
    width: 50%;
  }
  .container {
    flex-direction: row;
  }
}
<div class="container">
  <div class="item">content</div>
  <div class="item">content</div>
</div>

I expected the layout to be responsive, with items displayed in columns when the screen width is under 700px, and in rows with a width of 50% when the screen width exceeds 700px. However, it seems that only the width: 50%; property is being applied.

This is an image:

Answer №1

In order to ensure proper alignment, you must take into consideration the .item elements' border-left-width, border-right-width, margin-left, and margin-right. When the viewport width exceeds 700px, each .item element occupies a specific amount of horizontal space:

50% + 10px + 10px + 1px + 1px = 50% + 22px
 ↑      ↑      ↑     ↑     ↑
`width` │`margin-right`    │
        │            │     │
  `margin-left`      │`border-right-width`
                     │
          `border-left-width`

This means that for 2 items with a width of 50% + 22px, the total width would exceed 100%, which is the width of .container, resulting in wrapping at viewport widths greater than 700px.

To keep them on the same row, adjust their width by accounting for the excess space caused by horizontal borders and margins. Subtract the extra space, 22px, from 50%:

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

.item {
  margin: 10px;
  border: 1px solid lightgray;
  border-radius: 10px;
  overflow: hidden;
  width: 100%;
}

@media screen and (min-width:700px) {
  .item {
    width: calc(50% - 22px);
  }
  .container {
    flex-direction: row;
  }
}
<div class="container">
  <div class="item">content</div>
  <div class="item">content</div>
</div>

Alternatively, you can set flex-wrap: nowrap on .container. This will force the .item elements to be displayed in a row by adjusting their widths accordingly:

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

.item {
  margin: 10px;
  border: 1px solid lightgray;
  border-radius: 10px;
  overflow: hidden;
  width: 100%;
}

@media screen and (min-width:700px) {
  .container {
    flex-direction: row;
    flex-wrap: nowrap;
  }
}
<div class="container">
  <div class="item">content</div>
  <div class="item">content</div>
</div>

Answer №2

Your current CSS code specifies a minimum width of 700px, meaning the styles inside the media query will be applied when the screen width is at least 700px. If you want the styles to be applied when the screen width is less than 700px, you should use max-width: 700px instead.

Additionally, your flex-direction property is set to column for the container, which stacks items vertically. To change this so that the items are stacked horizontally, you should use flex-direction: row instead.

To make these changes, update your CSS code as shown below:

.container {
    display: flex;
    justify-content: center;
    align-items: center; 
    flex-wrap: wrap;
    flex-direction: column; 
}
.item {
    margin: 10px;
    border: 1px solid lightgray;
    border-radius: 10px;
    overflow: hidden;
    width: 100%;
}
@media screen and (max-width: 700px) {
    .item {
        width: calc(50% - 22px);
    }
    .container {
        flex-direction: row; 
    }
}
<div class="container">
  <div class="item">content</div>
  <div class="item">content</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

Displaying JSON data with dynamic color changes in an HTML table: A comprehensive guide

Scenario: I am currently working on a project where I need to fetch data from an external json file, parse it, and then dynamically add it to an HTML table using the footable jQuery plugin. Question: I have a query regarding how to use JavaScript to parse ...

Adjust the alignment of items in the NavBar using BootStrap to ensure they

I'm having trouble centering the contents of my Nav Bar, and for some reason, everything seems to be left-aligned instead of centered. I haven't used float: left anywhere, so I'm not sure why it's not working as expected. The goal is ...

Innovative HTML5 Video Canvas Shapes

I'm currently working on creating a circular frame or canvas for live HTML5 Video. While I am able to round the corners using keyframes radius property, it results in an oval shape rather than a circle. My preference would be to utilize a div object ...

How can triple nested quotes be utilized within Django templates?

Currently, I am attempting to utilize inline CSS and load an image as a background in a Django template. My goal is to include three quotes, however, I am unsure of the correct way to achieve this. Can anyone provide guidance on how to properly modify the ...

The class "Accordion" is not recognized by the local Bootstrap 5 installation

Currently, I am trying to implement a vertically collapsing Accordion using the Bootstrap 5 documentation found at https://getbootstrap.com/docs/5.0/components/accordion/ Even though I have installed the library with libman, Visual Studio 2019 is showing ...

The http url on an iPad in the src attribute of an HTML 5 video tag is malfunctioning

Having trouble loading a video on iPad using an http URL in the src attribute of an HTML5 video tag. Both static and dynamic approaches have been attempted, but it works fine on web browsers. Here is an example of the code: Static: <!DOCTYPE html ...

Creating a table with adjustable row heights is a great way to enhance the user

Can the height of an HTML table row be adjusted dynamically by dragging and dropping, similar to how it's done in this demo (https://reactdatagrid.io/docs/row-resize), but for free? ...

Mpdf does not support inline CSS rendering

I recently implemented Mpdf into my Symfony project using Composer. The installation process involved running the following command: composer require mpdf/mpdf Next, I included the Mpdf.php file in autoload.php. Here is an example of how to use Mpdf in ...

OutOfMemoryError caused by Bitmap

I'm experiencing an issue with this error. I created a favicon parser from URLs using the following code: public class FavIconParser { public static String extractUrl(String url) { StringBuffer sb = new StringBuffer(); Pattern p = Pattern.co ...

What is the best way to reset the 3rd dynamic dropdown menu once a new selection is made in the 1st dropdown menu?

I have been working on creating a dynamic dropdown using Jquery ajax and json in js. Almost everything is working as expected, except for one issue that I am facing. The problem arises when I select an option in dropdown A, which then loads items into drop ...

The impact of CSS positioning relative on the height of an element

I need help with positioning elements in my HTML layout. I have one element stacked below another and am using relative positioning to nudge the bottom element up slightly so that it overlaps the top element. The paperOverlay element is positioned at the ...

Is it possible to turn off the shadow on just one side?

Is there a way to remove the shadow in the red area below? I have come across similar questions but unsure how to implement those solutions here. Live Demo: http://jsfiddle.net/xFa9M/ CSS:- #list li{ border: 2px solid black; border-top-width: 1px; borde ...

Creating a standalone Wordpress child theme with its own CSS

After creating a child theme based on the responsive i-transform theme from http://templatesnext.org/itrans/, I found myself continuously undoing the i-transform CSS, which is taking up a lot of my time. However, if I remove the entire parent stylesheet, t ...

What is the best way to use appendChild within an AJAX get function to manipulate the DOM

I've been working on a code function where I try to append a list item (li) into the HTML received in 'msg', but it's not functioning properly. Any ideas why? function handleFileSelect(evt) { var files = evt.target.files; $(&ap ...

Tips for setting up personalized breakpoints for a Bootstrap navbar

I am currently facing an issue with my navbar on tablet view. Despite implementing custom breakpoints to collapse the navbar at 1050, the menu bar is appearing in two rows instead of one. I have tried using the code below but it doesn't seem to be wor ...

"Enhance Your Table Design with Zebra Cells Using CSS in rich:data

How can I achieve a zebra color effect in every other cell of a rich:dataTable using CSS? <rich:dataTable value="#{uploader.files}" var="_data" id="files"> <rich:column> <f:facet name="header"> <h:outputText ...

How to set up a Carousel as the background within a div using Bootstrap 5

I'm attempting to create a visually appealing layout by showcasing a Carousel component behind some text. The idea is to have scrolling and fading images with a prominent header overlaid on top of them. I want the carousel images to be contained withi ...

Navigating the elements within R Shiny: A comprehensive guide

Can anyone help me figure out how to access specific elements in my Shiny app using their HTML tags? In this particular example, I need to retrieve all h1 elements along with their respective labels and IDs. library(shiny) ui <- fluidPage( h1("Get" ...

How to retrieve a nested array element in JavaScript

Here is the Pastebin link of the index.html file for reference: http://pastebin.com/g8WpX6Wn (The file contains broken image links and no CSS styling). If you would like to access the entire project, you can download the zip file. I am currently working ...

What is the best way to conceal floated elements with overflow in CSS?

How can I ensure that my block container element only displays the content of block elements, cutting off any floated elements that are taller than the parent container? Applying overflow: hidden seemed like a simple solution, but it created a new block f ...