Determine the optimal width for each element based on the total number of instances of that element present

If there is an unknown quantity of elements, could they be expanded in the following manner:

1 element:
[========]

2 elements:
[===][===]

3 elements:
[===][===]
[========]

4 elements:
[===][===]
[===][===]

The [===]'s represent elements.

To add a strange twist to this query, this page will only ever be viewed in webkit, so -webkit elements are permissible even without -moz equivalents.

Is there a CSS-only solution to this issue? If not, is there a minimally-JS way to solve it?

Answer №1

Imagine having a markup structure like this:

<div class="container">
    <div>1</div>
</div>

<div class="container">
    <div>1</div>
    <div>2</div>
</div>

<div class="container">
    <div>1</div>
    <div>2</div>
    <div>3</div>
</div>

To achieve the desired layout, you can use the following CSS:

.container div {
    float: left;
    width: 50%;
}
.container div:last-child:nth-child(2n+1) {
    width: 100%;
}

This code essentially sets the width to 50%, but when there's an odd-numbered last child, it changes the width to 100%. You can see a complete example here.

Answer №2

Using JQuery, accomplishing this task is quite simple. Here's an example:

$(".box").each(
    function(counter, item) {
        if (counter > 0) {
            var previous = $(item).prev();
            if (previous.width() >= $(item).width()) {
                var newWidth = $(previous).width()/2;
                $(previous).width(newWidth);
                $(item).width(newWidth);
            }
        }
    }
);

In the code above, "box" represents the class name of the elements you are targeting.

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

Codeigniter: Troubleshooting Session Variable Issues

Hey there! I'm facing an issue with my session variable in Codeigniter. I have set the session variable in my model, but when I try to access it in my view through the controller, the value of the session variable becomes null. Any suggestions on how ...

Activate the button when the password is correct

Check out my code snippet: $("#reg_confirm_pass").blur(function(){ var user_pass= $("#reg_pass").val(); var user_pass2=$("#reg_confirm_pass").val(); var enter = $("#enter").val(); if(user_pass.length == 0){ alert("please fill password ...

How can I dynamically update the value of an ng-option based on the selection of another ng-option?

My application has 2 select option boxes. The first box contains a list of countries, and I want the second box to update its values based on the selection made in the first box. For instance, if I choose India from the first select box, the second select ...

Various Ways to Add Hyperlinks in HTML Using CSS Styles

Does anyone know how I can link multiple HTML files to one hyperlink, where only one file opens randomly when clicked? I am currently using . Your assistance would be greatly appreciated! I've tried searching online for a solution, but haven't ...

The outcome of the Bootstrap 4 grid layout was not what I had anticipated

When referring to the Bootstrap4 documentation, we find classes like col-*-num and offset-*-num for structuring page layouts. In the code snippet below, the column divisions from sm size and up are consistent, but there is a discrepancy in the layout for t ...

Only apply prevent default on specific levels for better control

I am currently working on a menu with submenus. I am facing an issue where when I click on a top-level menu item, I need to use prevent default because they are anchor tags. However, for the submenu items, I do not want to prevent default behavior. I am st ...

Custom AngularJS directive fails to reflect changes in model after selecting a file

I recently created a custom directive called ng-file-chosen, which is supposed to capture the selected file name from an <input> element and bind it to the ng-model passed in. In the code snippet below, the result of ng-file-chosen is linked to mode ...

Guide for adding an OnClick event to a MatTable row:

I am looking to add functionality for clicking on a specific row to view details of that user. For instance, when I click on the row for "user1", I want to be able to see all the information related to "user1". Here is the HTML code snippet: <table ma ...

Updating a section of a webpage using jQuery Mobile

I'm currently facing an issue with modifying a specific section of my webpage. Although this problem has been discussed before, I haven't found a satisfactory solution yet. The element in red on the page needs to change dynamically based on the ...

Switch from using a button element for user input to using a text input field when

I am encountering a simple issue. I want to initiate an ajax call using the following button <input type="submit" value="My Button" id="get" /> The challenge is that I prefer not to use a button, but rather plain text for activation instead of a c ...

Is a webpage's sluggishness in Internet Explorer due to its lengthy page structure causing issues while loading quickly on other browsers?

My application has a page that is particularly long, around 8Mb of source HTML mainly comprised of tables. I am aware that this indicates poor architecture, but unfortunately, I am unable to make immediate changes due to certain constraints. In most brows ...

How to wait for the webpage to fully load before executing a script using a Chrome extension

After opening a new website tab, I am attempting to select a DOM element by its class name. The issue I have encountered is not knowing how to effectively wait until the entire page has finished loading. Despite trying various methods such as alarms, setTi ...

Having difficulty executing the overridden doPost method in a Java servlet

Included below is a snippet of code extracted from a jsp file. <table class="table table-striped table-hover table-responsive ezoo-datatable"> <thead> <tr> <th class="text-center">Schedule ID< ...

Conceal the button briefly when clicked

How can I disable a button on click for a few seconds, show an image during that time, and then hide the image and display the button again? HTML: <input type="submit" value="Submit" onclick="validate();" name="myButton" id="myButton"> <img st ...

What is the best way to compress @font-face using gzip?

Could you demonstrate how to gzip a webfont kit? The code provided by the generator is as follows...what modifications are necessary? @font-face { font-family: 'DesigersBold'; src: url('desib__-webfont.eot'); src: url(&apos ...

What is the best way to create a scroll bar within a table while ensuring that the rows expand to fill the entire width?

I am attempting to design a table with 4 columns and a minimum of 12 rows while utilizing overflow-y:scroll. The webpage is completely responsive. I understand that in order to incorporate a scrollbar into the table, I must specify display: block for both ...

Content is not centered with Bootstrap's flexbox

The alignment of content is not centered using bootstrap flex <div class="d-flex flex-row bd-highlight mb-3"> <div class="p-2 bd-highlight text-left"><i class="fa fa-chevron-left" aria-hidden="true"></i></div> <div cla ...

Tips for emphasizing a specific cell in a row based on its expiration date

In my quest to find a script that colors dates within two weeks from today in red and past dates in orange, I have tried various methods without success. I am struggling to implement this feature with my current knowledge. <TABLE> <TR><TD&g ...

Locking the axis labels to the top of the plot in R shiny

My giraffe rendering is very long, and I want the x-axis values to remain visible as the user scrolls down. Below is a sample code that demonstrates this concept. I am open to different types of plots as long as they display the labels when hovering over ...

Initiating a horizontal scroll menu at the center of the screen: Step-by

I need assistance setting up a horizontal scrolling menu for my project. The requirement is to position the middle button in the center of the .scrollmenu div. Currently, I am working with HTML and CSS, but open to suggestions involving javascript as well ...