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

Several radial progress charts in JavaScript

While attempting to recreate and update this chart, I successfully created a separate chart but encountered difficulties with achieving the second progress. The secondary chart <div id="radial-progress-vha"> <div class="circle-vha ...

What is causing my div to transition repeatedly from the bottom to the top instead of the center position?

Currently, I am using React and Tailwind CSS and facing an issue with the transition property. My goal is to have a div grow in width and height from the center until it covers the entire viewport when a specific state variable becomes true. The content in ...

The font-family CSS properties inheritance is not functioning as I had anticipated

I'm currently working on a webpage where I want to add a list of links that resemble tabs. While this style is functioning correctly for the main pages, I'm having trouble implementing it for a new section. The existing list is located within: ...

Sleek and versatile sidebar reaching full height

Is there a way to make my sidebar cover the full height of the screen without using position: fixed? The code I've tried doesn't seem quite right. Any tips? JSFindle: http://jsfiddle.net/Pw4FN/57/ if($(window).height() > $('#page-contai ...

The appearance of Bootstrap React Nextjs doesn't quite match what's shown in the documentation

I am developing the frontend of my application using a combination of bootstrap, react, and nextjs. I attempted to implement the example provided by react-bootstrap at https://codesandbox.io/s/github/react-bootstrap/code-sandbox-examples/tree/master/basic. ...

Center align the division within the list item

Check out the fiddle provided here: https://jsfiddle.net/5jnnutg8/ I am looking for a way to center align and display inline the "something #" list items. While the title "Hi" can be centered using text-align: center in css, this doesn't seem to wor ...

Bidirectional updates in AngularJS with CSS styling

On the backend, certain HTML elements store their position and size persistently and retrieve them when the page loads. These elements can be dragged and resized by users, with any updates needing to be saved on the backend for consistency across sessions. ...

CSS - Creating a stylish break line for link boxes

Struggling with creating a box that includes linked text and a line break. However, the issue arises when the line breaks, causing the box to also break. After trying multiple options, I still can't seem to find a solution. Check out my attempt her ...

The color of the text changes from its default color when not in use

Hey there, let me break this down for you... I'm currently in the process of styling a contact form. I've managed to change the text color of my input focus to white. However, when I click away from the form, the inputted text color reverts ba ...

React js background image not filling the entire screen

Having experience with React Native, I decided to give ReactJS a try. However, I'm struggling with styling my components because CSS is not my strong suit. To build a small web application, I am using the Ant Design UI framework. Currently, I have a ...

Is it permissible to utilize the ::Before::Before element?

While working on a CSS file for a page with a non-editable profile, I encountered the challenge of not being able to add content directly. This limitation prompted me to explore alternative solutions. My idea was to utilize the page ID and incorporate it ...

Is there a way to prevent tags from wrapping and showcase them all in a single line when utilizing the jQuery select2 plugin?

I have a requirement to prevent tags from wrapping and instead display them in a single line using the jQuery TagIt plugin. Check out my preview: https://i.stack.imgur.com/lYhsi.png My goal is to have all the tags displayed on a single line without wra ...

The navigation bar and text subtly shift when displayed on various devices or when the window size is adjusted

Hello, I am brand new to web development and have encountered an issue on my website. Whenever the window is resized or viewed on a different screen, the navigation bar (which consists of rectangles and triangles) and text elements start moving around and ...

The paragraph element is refusing to align with the next paragraph element on the following line

The issue I'm facing is that the paragraph element is not displaying on a separate line from the other paragraph element. body { margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; height: 100vh; backgr ...

The functionality for dragging elements is not functioning properly in JavaScript

Here is the code I used in an attempt to make a div element draggable: let div = document.querySelector('div') div.onmousedown = function() { div.addEventListener('mousemove', move, true) } window.onmouseup = function() { window. ...

jQuery Refuses to Perform Animation

I'm facing an issue with animating a specific element using jQuery while scrolling down the page. My goal is to change the background color of the element from transparent to black, but so far, my attempts have been unsuccessful. Can someone please pr ...

Adding style using CSS to a dynamically generated table row in Vue.js

Currently, I am working with a table that dynamically generates rows using v-for: <table> <tr><th class='name'>Name</th><th>Surname</th></tr> <tr v-for='data in datas'><td class=&a ...

Manipulate component properties using CSS hover in React with Material-UI

I am attempting to modify the noWrap property of a Typography element when hovering over it. I have defined a custom CSS class for the parent element and the hover functionality is working correctly. However, I am unsure how to adjust the noWrap property u ...

Creating a CSS template for organizing sidebar and footer divisions on a webpage

I am facing an issue with the layout of my website. I have a container that is positioned relatively and houses various divs for header, sidebar, main-content, and footer. The problem lies with the sidebar and footer components. The sidebar has been posit ...

Center Align Images in HTML List Items

Hey there! I'm currently diving into the world of web development with responsive design, but I'm still a bit of a newbie. So please bear with me as I try to explain my issue in detail. If you need more information, just let me know! My current ...