Boxes that expand to full width and appear to float on

I am dealing with a situation where I have a container that holds multiple child elements such as boxes or sections.

<section>
    <div>Box 1</div>
    <div>Box 2</div>
    <div>Box 3</div>
    <div>Box 4</div>
    <div>Box 5</div>
    <div>Box 6</div>
    <div>Box 7</div>
    <div>Box 8</div>
    <div>Box 9</div>
    <div>Box 10</div>
</section>

These child elements each have a minimum width and are floated left. Depending on the parent container's width, a specific number of children should be displayed in a row.

section {
    min-width: 150px;
    font-family: 'Segoe UI', Ubuntu, sans-serif;
}

div {
    min-width: 150px;
    height: 150px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;

    float: left;
    margin: 0 3px 3px 0;
    padding: 3px;
    background-color: lightblue;
    border: 1px solid #000;
}

To achieve this layout, I would like the children to fill the entire width of the parent container if it is between multiples of the child element's width. For example, if the parent container's width is 660px, each child should be 165px wide. Additionally, any changes in the parent container's width should automatically adjust the children's widths.

I have explored using media queries for my specific case, but I am seeking a more general solution that can handle variable parent container widths. While I am open to utilizing JavaScript/jQuery, the solution should gracefully degrade in older browsers and be compatible with modern browsers like IE 10+, Firefox, Chrome, and Safari.

Initially, I attempted to use flexbox, but encountered issues in Firefox due to its limited support for single-line flexbox. As a result, I turned to JavaScript based on Siddhartha Gupta's suggestion. However, there seems to be a bug where sometimes the rows do not completely fill the available space.

$(window).resize(function () {
    var sectionWidth = $('section').width(),
        childWidth = (sectionWidth / Math.floor(sectionWidth/150)) - 3;

    $('section').children().css({
        'width': childWidth + 'px'
    });
});

Answer №1

Check out this code snippet

let sectionWidth = $('section').width();

// Calculate width of each child element
// Divide parent width by number of children to show
// Subtract 2px for border and padding
let childWidth = sectionWidth / 8 - 2 - 2;

// Apply the calculated width to each child element
// Also remove any min-width property
$('section').children().css({'min-width': 0, 'width': childWidth + 'px'})

Answer №2

Here is an alternative method to achieve the same outcome (inspired by S.Gupta's answer)

let a;
function anotherFunc(){
let sectionWidth = $('section').width();  
let minChildWidth = 150; // specify minimum width here  
let k = Math.floor(sectionWidth/minChildWidth);
if(k!=a){
k = 100/k;  
$('section').children().css({'width': k + '%'});
}
a=k;
}

This approach might be more efficient as it avoids recalculating and applying widths repeatedly, leveraging percentage-based widths. For finer adjustments, consider slightly subtracting from the final calculated value like 0.1 or 0.5%. For even more precise control, create wrappers for the inner divs and manage widths through containers rather than individual elements.

If avoiding jQuery is preferred, the following vanilla JavaScript solution can be considered:

JS:

let a;
function bar(){
let s = getElementById('section_id');
let minW = 150; 
let sWidth = s.offsetWidth;
let k = Math.floor();
k = (k>5)?5:k;
if(a!=k)
s.className="m"+k;
a=k;
}

CSS:

.m1 .inner_div {width:100%}
.m2 .inner_div {width:50%}
.m3 .inner_div {width:33.3%}
.m4 .inner_div {width:25%}
.m5 .inner_div {width:20%}
...
.section {width:100%}

While this approach has its limitations based on the predefined number of columns, it can still prove useful in certain scenarios where responsiveness is key. It is particularly effective when the inner divs have distinct minimum and maximum widths. Your feedback is welcomed.

--
Using jQuery may result in performance issues with numerous div elements undergoing width adjustments during window resizing. In cases where columns are limited due to specific width constraints, opting for a non-jQuery solution could be beneficial, ensuring smoother transitions without sacrificing functionality.

Any thoughts or suggestions are encouraged.

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 could be causing the page to automatically scroll to the bottom upon loading?

My experience with this bootstrap/jquery page in Firefox (v39, latest updates installed) has been unusual as it always seems to jump to the bottom of the page upon clicking. Upon inspecting the code, I couldn't find any JavaScript responsible for thi ...

Optimizing CSS for Landscape Letter Print Alignment

When attempting to print in letter size and landscape orientation, the two divs fail to align properly. However, when using "@size a4 landscape" for printing, the alignment issue is resolved. What could be missing from my print CSS that would allow them to ...

Is there a way to make two parallelograms overlap seamlessly and adjust in size automatically using HTML?

Recently delving into the world of HTML and CSS, I've set my sights on designing something unique involving parallelograms that adjust dynamically. My vision includes four overlapping parallelograms starting from the top at 25%, 50%, 75%, and finally ...

Role-based dynamic layout

I am currently working on a website that requires user login functionality. To achieve this, I am utilizing materialise-css and Angularjs for the front-end development, while the back-end is powered by Java-Hibernate (as Spring is not an option in my case) ...

Populate modal form with database information without using Bootstrap

As I work on populating a form with data from an sqlite database, I've come across a stumbling block. My code is available for reference on JSFiddle: https://jsfiddle.net/daikini/e71mvg7n/ One important note: Bootstrap isn't being utilized in t ...

Tips for minimizing excess white space in Shiny applications

Encountering an issue with plot output in Shiny. When using standard ggplots, the output is correct without any extra white margins. However, when utilizing the "ggmap" package (which also produces ggplot-type outputs), white margins suddenly appear. (Ple ...

What is causing the section to cover the navbar?

My content is overlapping the navbar on certain screen sizes, and I'm not sure why. Any ideas on how to fix this issue? Would wrapping everything in a container help? Currently using bootstrap v5.3.0-alpha1. Additionally, when I have a collapsed nav ...

Focusing on the initial element following CSS prioritization

Check out this codepen link: http://codepen.io/muji/pen/XpEYzO I am looking to target the first element after it has been sorted using a CSS "order" property and apply another CSS property to it. Is there a way to use jQuery or any other method to identi ...

Using Express.js to serve simple SVG files (Technique involving Cheerio.js)

My goal is to manipulate SVGs before sending them through Express.js. The code snippet I am using is as follows: app.get("/iconic/styles/:style/:base/:icon", function (req, res) { var style = req.params.style; var base = req.params.base; var i ...

Showing information retrieved from a database using PHP in a sequential manner

I'm currently working on developing a webpage that features 6 rows of images, with each row containing 4 images accompanied by captions right below them. The structure I have in mind is as follows: IMAGE IMAGE IMAGE IMAGE TEXT TEXT TEXT TEXT IMAGE ...

Issue with jquery_ujs: Font Awesome spinning icon animation functions properly in Chrome but not in Safari

I've integrated font-awesome-rails into my Rails project. When a user clicks the submit button on a form: The submit button should display an animated font-awesome spinner and change text to "Submitting...". The button must be disabled to prevent m ...

Error TS7053 occurs when an element is given an 'any' type because a 'string' expression is being used to index an 'Object' type

When attempting to post data directly using templateDrivenForm and retrieve data from Firebase, I encountered the following type error message. Here are the relevant parts of my code: // Posting data directly using submitButton from templateDrivenForm onC ...

What is the best way to incorporate both images and text in PHP code?

I'm currently working on creating a large image call-to-action (CTA) for my new WordPress website. I've set up a new field group with the type "group" in ACF, and added some functions in PHPStorm. However, none of my images, text, or links are ap ...

What methods can I use to display or conceal certain content based on the user's location?

I'm looking to display specific content exclusively to local users. While there are APIs available for this purpose, I'm not sure how to implement them. I'm interested in creating a feature similar to Google Ads, where ads are tailored base ...

A step-by-step guide to incorporating expandable and collapsible images within a div element using X

I have successfully created dynamic divs with some data that expand and collapse perfectly. Now I am looking to add expand and collapse images on these divs. I am relatively new to designing in xslt. <xsl:template match="category[key!='org.model.C ...

Ways to include scrolling specifically for one template

As a newcomer to frontend development, I have recently started learning Vue and the Quasar Framework. I am currently working on a table and trying to set a fixed table name with only the table items scrollable. <template> <q-table virt ...

What is the best approach to make the child element function properly within my CSS grid design?

I've been struggling to set up a 3-column grid with 2 rows for showcasing my projects on my portfolio. Unfortunately, they are only appearing in the first column and I can't figure out how to fix it. Here's a visual representation of the is ...

Function in jQuery to reference two different divs

I'm currently facing an issue with a code snippet that I have. The requirement is for the user to be able to hover over "Div 1" and/or "Div2" and trigger a red border around both elements simultaneously. Due to the complexity of my WordPress theme, th ...

The element cannot be clicked at this point as another element would intercept the click:

Having an issue with clicking a button at the top of the page. The CSS selector works fine in my local Eclipse environment, but when trying to run it on Jenkins server on my local machine, it fails with an error stating that the element is not clickable. T ...

Designing stylesheets for larger screens to optimize the layout

I am currently working on the front-end design of a website and could use some assistance regarding element sizing. While the layout and elements look great on my 19-inch, 1440x900 resolution monitor, I noticed that everything appears tiny when viewed on a ...