Discovering the solution to creating a responsive element grid using only CSS: (8-1) - (4-2) - (2-4) - (1-8)

My responsive website includes the following HTML code:

            <div id="fpma">
                <span class="fpm"></span>
                <span class="fpm"></span>
                <span class="fpm"></span>
                <span class="fpm"></span>
                <span class="fpm"></span>
                <span class="fpm"></span>
                <span class="fpm"></span>
                <span class="fpm"></span>
            </div>

The width of #fpma container varies based on the screen size, while the elements within .fpm have fixed widths. The current CSS looks like this:

#fpma {
    text-align: right;
    width: 100%;
}

.fpm {
    width: 48px;
    height: 33px;
    display: inline-block;
    margin: 4px;
    background:url('images/bar.png') center center no-repeat;
}

I am seeking a reusable solution to automatically rearrange the items as the parent container's width decreases in the following manner:

1 row - 8 elements

2 rows - 4 elements

4 rows - 2 elements

8 rows - 1 element

I would prefer a solution that does not rely on media queries and allows for flexibility without requiring additional wrappers in the HTML structure.

If utilizing CSS3 features like nth-child, :before/:after, flexbox, etc., is necessary, it is welcomed. However, any solution should aim to avoid dependency on media queries due to their fixed max-width/min-width constraints. If providing a media query alternative along with reasons for its necessity, that would also be acceptable. I have experimented with various approaches but have yet to achieve the desired result.

If needed, changing the display form of the elements is permissible.

Answer №1

To achieve this, you need to utilize @media queries in conjunction with setting fixed sizes for elements within the .fpm class. This will allow you to determine when the @media query should trigger a layout change for 2 rows, 4 rows, or 8 rows. I have provided an example for 2 rows using the same logic that can be applied to 4 and 8 rows as well.

#fpma {
    text-align: right;
    width: 100%;
    box-sizing:border-box;
    border:1px solid red;
}

.fpm {
    width: 48px;
    height: 33px;
    display: inline-block;
    box-sizing:border-box;
    border:1px solid #000;
    margin: 4px;
    background:url('images/bar.png') center center no-repeat;
}
@media screen and (max-width:408px){
  #fpma:before, #fpma:after {
    content: "";
    display: table;
  }
  #fpma:after {
    clear: both;
  } 
  #fpma {
    *zoom: 1;
  }
  .fpm {
    float: right;
  }
  
  .fpm:nth-of-type(5n) {
    display: inline;
    clear: right;
    float: right;
  }
}
<div id="fpma">
                <span class="fpm">1</span>
                <span class="fpm">2</span>
                <span class="fpm">3</span>
                <span class="fpm">4</span>
                <span class="fpm">5</span>
                <span class="fpm">6</span>
                <span class="fpm">7</span>
                <span class="fpm">8</span>
            </div>

https://jsfiddle.net/vm0opbab/

I believe I have implemented the solution correctly.

Answer №2

To achieve this layout, you will need to utilize media queries or scripting. Here is a basic example using media queries:

Check out the demo on Fiddle

Here is a snippet of code:

#fpma {
  width: 100%;
}
.fpm {
  width: 48px;
  height: 33px;
  float: right;
  margin: 4px;
  background:url('http://placehold.it/100') center center no-repeat;
}

@media screen and (max-width: 450px) {
  .fpm:nth-of-type(5) {
    clear: right;
  }
}
@media screen and (max-width: 225px) {
  .fpm:nth-of-type(3),
  .fpm:nth-of-type(7) {
    clear: right;
  }
}
@media screen and (max-width: 112px) {
  .fpm {
    clear: right;
  }
}
<div id="fpma">
  <span class="fpm"></span>
  <span class="fpm"></span>
  <span class="fpm"></span>
  <span class="fpm"></span>
  <span class="fpm"></span>
  <span class="fpm"></span>
  <span class="fpm"></span>
  <span class="fpm"></span>
</div>

Answer №3

I have managed to find a solution for 3 out of the 4 cases.

By utilizing flexbox properties and adjusting margins, I was able to achieve the desired effect.

#container {
  width: 581px;
  height: 450px;
  border: solid 1px red;
  display: flex;
  flex-wrap: wrap;
  animation: widen 6s infinite;
}

.box {
  width: 48px;
  height: 50px;
  border: solid 1px blue;
  flex-shrink: 0;
}

.sep1 {
  margin-right: 150px;
}

.sep1 + div {
  margin-left: -150px;
}

.sep2 {
  margin-right: 50px;
}

.sep2 + div {
  margin-left: -50px;
}

@keyframes widen {
  from {width: 110px;}
  to {width: 450px;}
}
<div id="container">
    <div class="box">A</div>
    <div class="box">B</div>
    <div class="box sep2">C</div>
    <div class="box">D</div>
    <div class="box sep1">A</div>
    <div class="box">B</div>
    <div class="box sep2">C</div>
    <div class="box">D</div>
</div>

However, the requirement for rows containing only 1 element remains unresolved...

Perhaps someone else can offer a solution to this final issue?

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

What is preventing this Node JS code from successfully serving a static PNG file?

To the administrators, I have spent hours scouring various resources for answers related to Node Js, Express, and serving static files. Despite my efforts on stackoverflow and other platforms, I have yet to find any solution that works for me. If my questi ...

Conceal the horizontal scrollbar when the navigation menu is minimized

Explaining this concept may be a bit challenging, so I have included a jsfiddle demo. The issue at hand involves a bootstrap nav menu that shifts to icons when not active and expands to include words when focused. When the menu is expanded, there are no sc ...

User's information will only be updated once the page is refreshed

I am encountering an issue with displaying two ul elements based on user login status. When I log in, the first ul is shown immediately, but the second ul is only displayed after a page refresh. Initially, the value in "accountService.currentUser" is null ...

Is there a way to customize my visual studio code to automatically insert an indented space between curly brackets in CSS when I press enter?

Whenever I try to open curly brackets in CSS and press enter, it simply moves to the next line without adding an indentation as shown below: body { } Despite going through the settings and experimenting with different options, I haven't been able to ...

Issues with concealing the side menu bar in Vue.js

I've been attempting to conceal the side menu bar, with the exception of the hamburger icon when in the "expanded" state. Despite my efforts to modify the CSS code, I am still struggling to hide the small side menu bar. The following images represent ...

When a button is clicked, unleash the magic of music using JavaScript

Why isn't the button onclick working for the mp3 file I uploaded to GitHub? I even tried using the link through https://voca.ro/1dcHxW3v1oQA, but it still wouldn't work. function play() { var audio = new ...

My customized portfolio incorporates Bootstrap 4 and integrates a modal for collecting feedback. I am looking for a way to gather visitor feedback directly into a Google Sheet without relying on Google Forms

click here to view the image I am seeking feedback on my bootstrap modal from visitors. This portfolio is hosted in HTML and I am looking for a way to gather feedback without using a database, possibly through Google Sheets. ...

What is the best way to detect input events from the Stripe cardElement to determine if a card is invalid and then proceed to disable the button?

While my user fills out the form with order information and customer details, I ensure that the submit button remains disabled until all validations are met. The library being used for this purpose is express-validate. In addition to the current setup, I ...

How can I retrieve a list of downloads utilizing the Chrome.downloads api?

I have developed an extension that needs to display all the downloads from the user's downloads folder on a webpage instead of opening the download folder directly. Below is the code I have implemented: window.onload = function(){ var maxNumOfEn ...

Delete auto-generated list using handlebars JS

I have successfully created a dynamic list using Handlebars.js and its template. However, I am now facing confusion on how to remove or delete items from the list using a function or specific code. As I am new to Handlebars, I would appreciate any help. ...

The div on the right side is constantly adjusting its height, while the div on the left remains at a fixed height. They need to be

In the PHP code provided below, you will find the script responsible for generating the dynamic content on the right side of the page. The section tag and its associated content are dynamically created within this script. while($row = mysqli_fetch_object( ...

Unexpected Placement of Bootstrap 4 Table Spinner in Chrome and Internet Explorer

I am struggling to create a dynamic spinner within a table's tbody using Bootstrap 4. Here is what I have attempted so far: HTML <div class="container mt-2"> <div class="card"> <div class="card-body"> <div class="row"> ...

Altering an element's visibility from 'none' will trigger its animation to play once again

Take a look at the snippet below and you'll see that the sliding animation plays twice - once when the .addClass statement runs, and again when #test's display is switched to 'initial' (timeouts are in place to help visualize the issue) ...

Responsive Alignment of Slanted Edges using CSS

I have been working on creating a responsive diagonal layout with slanted shapes (refer to the image attached). However, I'm facing a challenge with aligning the edges smoothly at different screen sizes, especially when the rows grow and the screen re ...

Creating submenus that cause the navigation menu to drop down

I created a basic navigation bar using HTML Lists. The initial structure looks like this: <div id="menu"> <nav> <ul> <li><a href="#">My Profile</a></li> <li><a href="#" ...

Collection of clickable images that lead to creatively designed individual pages

Being relatively new to JavaScript and jQuery, my knowledge is solid when it comes to HTML & CSS. Currently, I have a page with 20 minimized pictures (with plans to increase to 500+ images) that open into a new page when clicked. Although I have no issues ...

Enhance your website with a dynamic jQuery gallery featuring stunning zoom-in

I am currently working on a mobile website project and I'm in need of a gallery feature that allows users to zoom in on images and swipe through them using touch gestures. After some research, I haven't been able to find a suitable solution in j ...

Encountered SyntaxError: An unexpected token has been found while integrating leaflet with flask

Despite adding all necessary scripts and configuring my API_KEY in config.js, I keep getting an error message saying "Uncaught SyntaxError: Unexpected token." I have double-checked my API key multiple times, and it seems to be correct. Here is a snippet f ...

Having trouble with the jQuery each function's functionality

I am creating circular counters for surveys by generating a counter for each answer option. Currently, I am utilizing this "plugin": Issue: The problem lies in the plugin not fetching the text value from the <div> element and failing to draw coun ...

Am I utilizing the htmlspecialchars function properly?

My main objective is to protect the user from malicious code and prevent XSS attacks. I have implemented a series of checks to filter the user's input before storing it in the database. The user input is stored in the $post variable. $post = htmlspec ...