What is the proper way to ensure a flex item takes up 50% of the space when a gap is included in

It appears that I have misunderstood something about flexbox and am struggling to resolve the issue correctly.

In my current setup, I have a flexbox container with four columns as its direct children. I want each .flexbox-item to take up 50% of the container's width when the browser window size reaches 992px or lower.

The challenge:
Everything seems to work fine without using the 'gap' property on the .flexbox-container. However, once I introduce gap: 1em, the percentages no longer function as expected. It seems like the gap value is affecting the overall calculation of widths for the .flex-item elements.

The query:
How can I ensure that each flexbox item indeed occupies 50% of the container's width when the browser viewport is 992px or smaller, even when the 'gap' property is used? While adjusting the 'width' property manually to 45% may work, it doesn't feel like the correct solution to me. I would appreciate guidance on the best approach to maintain accurate percentage sizing when utilizing the 'gap' property.

Below is the code snippet in question:

.flexbox-container {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  gap: 1em;
}

.flexbox-item {
  width: 25%;
  background-color: lightgreen;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}

@media screen and (max-width: 992px) {
  .flexbox-item {
    width: 50%;
  }
}
<div class="flexbox-container">
  <div class="flexbox-item">Item 1</div>
  <div class="flexbox-item">Item 2</div>
  <div class="flexbox-item">Item 3</div>
  <div class="flexbox-item">Item 4</div>
</div>

You can view the output here: https://jsfiddle.net/Erasus/gxtvhuow/12/

Answer №1

If you are looking to create a layout using either grid or flex, here is an example that demonstrates both methods. Feel free to adjust the code based on your specific requirements.

.flexbox-container {
 display: grid;
 grid-template-columns: auto auto auto auto;
 grid-gap: 1em;
 }

.flexbox-item {
  width: 100%;
  background-color: lightgreen;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.flexbox-container2 {
 display: flex;
 grid-gap: 1em;
 }


.flexbox-item2 {
  width: 100%;
  background-color: lightgreen;
  height: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}

@media screen and (max-width: 992px) {
.flexbox-container {
    display: grid;
    grid-template-columns: auto auto;
    
  }
  
.flexbox-container2 {
 display: flex;
 flex-wrap: wrap;
 grid-gap: 1em;
 }
 
 .flexbox-item2:nth-child(2n + 1),
 .flexbox-item2:nth-child(2n + 2) {
 flex: 0 0 calc(50% - 10px);
 
}
}
<h1>This is the grid way</h1>
<div class="flexbox-container">
  <div class="flexbox-item">Item 1</div>
  <div class="flexbox-item">Item 2</div>
  <div class="flexbox-item">Item 3</div>
  <div class="flexbox-item">Item 4</div>
</div>

<br>

<h1>This is the flex way</h1>
<div class="flexbox-container2">
  <div class="flexbox-item2">Item 1</div>
  <div class="flexbox-item2">Item 2</div>
  <div class="flexbox-item2">Item 3</div>
  <div class="flexbox-item2">Item 4</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

A Guide to Overflowing Text Above Divs - Even When the Parent Div has a Width of 0%

My webpage, built with Bootstrap 4, features a row with three divs placed horizontally. The divs have different percentage widths and sometimes the center div's width is set to 0%. However, I need to ensure that the text within the 0% div is always v ...

Ways to add more spacing between list items without affecting the position of the bottom div

I'm attempting to achieve a layout similar to an Instagram post, where the list expands but does not push the footer down. In my case, adding margin-bottom to the comment class affects the height of the <div class="post-details-container" ...

Injecting CSS styles into a webpage using a Chrome extension before the page has completely loaded to achieve instant customization

As a newcomer to creating Chrome (or other browser) extensions, I am working on developing one that applies custom CSS rules to specific page elements. Overall, it seems to be functioning as intended, but with some minor issues. One issue I have encounter ...

How to Generate HTML Reports Using JBoss?

Is there a convenient and efficient way to generate .html reports for JBoss applications that is not time-consuming? I have a database containing entities that I need to display in multiple tables. The report should include links to navigate between secti ...

What is the purpose of using square brackets in a CSS style declaration?

I've recently taken over the management of a website and I came across some unfamiliar CSS syntax. Has anyone encountered this type of syntax before? Can someone explain what the square brackets inside a style represent? Thank you, Rob .trigger-tx ...

Utilizing encoding and decoding techniques in PHP and JavaScript with robust data attribute validation

I am utilizing data attributes to transfer information from HTML to JavaScript. The data attributes are derived from MySQL data, so they may contain spaces, resulting in validation errors since spaces are not permitted within attributes. My proposed solut ...

Creating boxes with equal heights in HTML and CSS

I have created this menu using a combination of html and css. The layout consists of 3 boxes, each with different content. My goal is to ensure that all boxes are the same height within the design. However, due to specific responsive requirements, I cannot ...

What steps can I take to enhance the responsiveness and overall performance of this code using bootstrap?

Struggling with making your website responsive? No worries, we've all been there. Whether you're a pro at coding in react.js and vue.js or a complete beginner, we all need to start somewhere. Any suggestions or tips on how to improve responsivene ...

Struggling to delete a table row using jquery

Currently, I am encountering an issue with removing a specific "tr" element within a table using jQuery. Here's the situation: I have a table where rows are clickable. Upon clicking on a row, I can update the data associated with that particular obj ...

Using jQuery to enhance an HTML form

Currently, I am in the process of creating an HTML form for user sign up which includes typical fields such as username, password, and email. My intention is to transfer the entire HTML form to another .php file using the POST method. The second .php file ...

Mysterious failure of JavaScript regular expression when encountering the term "tennis"

We developed a JavaScript script to detect duplicates or potential duplicates, but it seems to have some issues with certain words like "tennis." The script functions correctly in most cases, but fails when analyzing phrases related to the word "tennis" fo ...

The Transformicons by Navicon featuring a stylish blue outline

While experimenting with the navicon from sara soueidan, I noticed a blue selector around the icons that I can't seem to get rid of. Is this something specific to the method used, or just a misunderstanding of jQuery? Here is the code snippet: http:/ ...

Navigating to a precise location on initial page load using Angular 11

Within the structure of my app, I have a parent component that displays a large image from a child component. When the parent component loads, I want the browser window to automatically scroll to a specific position in order to center the image. Currently ...

<container> rectangular form

.products { width: 100%; height: 500px; background: gray; } .box { width: 250px; height: 300px; background: darksalmon; border: 1px solid #000; } <div class="products"> <div class="box"> <p>Ola</p> </div> ...

Display validation in HTML5 only when the form is submitted

Here is the code snippet I am referring to: <input required pattern="[0-9]{5,10}" oninput="setCustomValidity('')" oninvalid="setCustomValidity('Type something')" /> I'm looking for a way to remove o ...

Updating the value of each preceding sibling of every checked checkbox using jQuery upon form submission

After extensive research, I discovered that the most effective approach involves using a clever workaround to capture every tick and untick on a dynamic input row with multiple checkbox arrays. However, none of the solutions provided a viable method. I th ...

jQuery only works partly with IE

I am attempting to utilize jQuery to modify some css styles when the screen size is smaller than a specific threshold (essentially, recreating "@media screen and (max-width: 1024px)", but with consideration for older versions of IE that do not support this ...

Ways to reduce the size of the background image in a select element?

Utilizing the bootstrap form-select select element : <select class="form-select listbox_length_menu_datatable" <option value='5'>5</option> <option value='10'>10</option> <option value ...

What is the best way to ensure that images on a webpage adjust to a maximum width without distorting smaller images?

I'm working on my website blog and I need to create a specific area for images at the top of my articles. I want these images to have a maximum width so they don't exceed a certain size, but I also want smaller images to remain unaffected. Curren ...

Navigating with Express while incorporating React

I am struggling to set up the routes for my web application using Express, as well as incorporating React for the front end. The issue lies in properly routing things when React components are involved. My index.html contains: <script> document.get ...