Distribute uniform width among child elements using CSS styling

In a fixed-width area, I may need to place either four divs or two divs based on different circumstances.

If there are only two divs, they should occupy 50% of the width each:

On the other hand, if there are four divs, they should be stacked like this:

Right now, I am using four divs with a width of 25%. How can I use CSS to dynamically adjust the size of the divs so that when there are only two, they cover the entire intended area just like the four divs do?

Edit

Sometimes, I may want to hide the orange section representing 225% and in those cases, I would need to stretch the yellow section along with the 200% part.

Answer №1

Consider the following example markup:

<div class="wpr">
    <div></div>
    <div></div>
    <div></div>
</div>

Solution #1 - Flexbox

.wpr {
  display: flex;
  width: 400px;
}

.wpr div {
  flex: 1 1 0;
  border: 1px solid yellow;
  background: pink;
  text-align: center;
  min-height: 40px;
}
<div class="wpr">
  <div></div>
  <div></div>
  <div></div>
</div>

<div class="wpr">
  <div></div>
  <div></div>
</div>

<div class="wpr">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Solution #2 - CSS tables with table-layout:fixed

.wpr {
    display:table;
    table-layout:fixed;
    width: 400px;
    min-height: 40px;
    
}
.wpr div {
    display:table-cell;
    border: 1px solid yellow;
    background: pink;
}
<div class="wpr">
    <div></div>
    <div></div>
    <div></div>
</div>

<div class="wpr">
    <div></div>
    <div></div>
</div>

Answer №2

To accomplish this task, one creative approach is to determine the width of each box based on the total number of boxes present.

This can be achieved effectively using CSS 3 with some clever techniques.

Consider the following HTML structure:

<div class="theContainer">
    <section>One</section>
    <section>Two</section>
</div>

<div class="theContainer">
    <section>One</section>
    <section>Two</section>
    <section>Three</section>
</div>

We can utilize the following CSS code:

.theContainer section:nth-last-child(2),
.theContainer section:nth-last-child(2) ~ section { width: 49%; }

In this selector, we are targeting the second element from the end within theContainer and its adjacent elements as well.

If we have enough elements, the selector will match the desired position when counting backwards. If not, the selector won't find a match. For instance, if we have 3 items and request nth-last-child(4), it will exceed the existing items and produce no result. Thus, our selector only applies when an item is found at a specific backward position.

.theContainer section:nth-last-child(3),
.theContainer section:nth-last-child(3) ~ section{ width: 32%; }

In this case, we are specifying the third section from the end along with its neighboring sections.

The first rule instructs the browser to identify all sibling sections within the div where the last child's position is either 3 or 2.

When the last child is 3, the width will be set to 32%. Similarly, for a last child of 2, the width will be adjusted to 50%.

You can view a demonstration of this solution in action on jsFiddle: http://jsfiddle.net/HreBe/

Answer №3

There are a couple of methods to achieve this task.

  • One way is to calculate the results using a server-side language. Assign a specific string to each div's class based on a switch or condition related to the count of results.
  • Another method involves counting the number of children in the parent container and distributing the desired width evenly among them.

In my opinion, the latter approach can be accomplished purely with CSS. The former approach, on the other hand, would necessitate the use of a server-side programming language.

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

Design a Bootstrap dropdown menu featuring various options within an icon container

I have designed a blade with a signboard containing multiple columns, each displaying its name, color, and assigned cards (screenshot). To enable sorting of these cards, I added an icon next to each column title. My goal is to allow users to select sorting ...

One webpage with various states managed by the URL conducted

After conducting a thorough search, I find it challenging to identify the precise terminology for my current inquiry. Mainly, my objective is to display a particular page state (showing/hiding a div) based on the URL. On a single page containing three di ...

Having difficulties linking my HTML form document to my PHP script

I have created a login form page on my website and am attempting to link it to a file named connect.php within the same directory. Here is the HTML content: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&q ...

How to use jQuery to display only the following div with a matching class

I'm encountering an issue while attempting to perform a series of steps using jQuery. Unfortunately, I am unable to achieve the desired outcome. There are 3 steps, each with a class of .wiki-step- followed by a number. Here is my JavaScript code: fu ...

Limit the rotation of jQuery and CSS3 elements to always turn in a clockwise direction

Utilizing the jQuery transit plugin, I am rotating a block element with 4 navigation controls. Each time a nav item is clicked, the block rotates to the specified custom data attribute of that nav item - either 0, 90, 180, or 270 degrees. While I have suc ...

Getting the draggable events area from the database in fullCalendar: A step-by-step guide

Currently, I am in the process of developing fullCalendar drag-and-drop events with a resource column. Initially, I hardcoded the draggable events area and now I am working on retrieving it from the database. Previously, the database had two tables - Resou ...

Progress Bar Has Wandered Off Track

Having trouble with two queries. Take a look at the live view here First Query: Struggling to position the progress bar below my image using CSS. Second Query: Want to make the images slide left instead of fading with the progress bar in my Javascript. ...

Execute two operations using jQuery and PHP

I recently created a form for users to fill out, with the data being sent to my email. However, I also wanted the email information to be posted to my MailChimp account using their API. Unfortunately, this feature is currently not functioning correctly. B ...

The table's pagination displays above, thanks to Tailwindcss

I'm facing an issue where the pagination is showing up above the table, but I was expecting it to be displayed after the table. It would be ideal if the pagination appeared right after the table when adding multiple rows. Check this link for more inf ...

Setting the background image of a div in my Angular application by utilizing the value returned from an API call

I'm currently working on a movie search application where I need to set an image as the background of a div. The URL for this background image is fetched from an API call. Here is what I have tried so far: <div *ngFor="let movie of movies.results ...

Final day of the month (without a time stamp)

Looking to generate two dynamic dates in HTML, JavaScript, and jQuery with the format yyyy/mm/dd. One should display the last day of the previous month, and the other the last day of the current month. Does anyone have a solution using these technologies? ...

Obtain several dropdown menus without their items displaying beneath the correct element

I'm currently in the process of setting up multiple drop down menus within a navigation element. The issue I'm facing is that when a user hovers over the menu items, the displayed elements appear below the first item instead of the selected one. ...

Ways to add vertical dimension to an image without distorting it

I'm dealing with an image that has a very high resolution. I've managed to set the width to 100% without any issues, but I'm struggling to find a way to set the height without stretching the image. Here's my HTML: <div class="conta ...

Floating motion when dragging

I am looking to create a hover effect while dragging an object over other objects. The catch is that the hoverable objects are inside an iframe, while the draggable object is outside the iframe. You can see what I am trying to achieve in this example ...

What is the best way to use res.send() to target a specific ID within an HTML tag in Node.js?

In my search.html file, I have the following form: <form class="myform" action="/classi" autocomplete="on"> <input type="text" name="search" > <button type="submit" ></button> Upon pressing the button, the following code in ind ...

What is the best way to preserve text input value when going back a page in PHP?

Is there a way to keep the text box value entered by the user even after navigating away from the page? Below is an example of what I am trying to achieve in my code: **main.php** <html> <head></head> <body> <i ...

A guide on customizing the appearance of individual items in a vue v-for loop based on specific conditions

I am currently developing a multiple choice quiz game and I want the selected answer by the user to change color, either red or green, depending on its correctness. To achieve this, I have created a variable called selected that correctly updates when the ...

How can I achieve a fade-in effect whenever the flag image is clicked?

A unique "international" quotes script has been created, showcasing Dutch, English, German, and French quotes. The script displays different quotes every day, with a draft-result visible in the upper right corner of this page ... The code used for this sc ...

I am having trouble aligning the unordered list in the center

My struggle lies in centering the ul element which serves as a menu. Despite trying various CSS properties such as margin: 0 auto;, text-align: center;, and adjusting the margin value, I am unable to achieve the desired result. This is the CSS code I have ...

Compress a CSS file with PHP

When using the code below to remove all newlines and spaces from a CSS file, it may cause an issue if the file contains the following: .sample { padding: 0px 2px 1px 4px; } The output will be: .sample{padding:0px2px1px4px;} However, I actually want ...