Creating a balanced height for child elements using CSS

If you are looking to display a list of colors with each color occupying an equal fraction of the height, here is how you can achieve it. Imagine presenting four colors in a list with a fixed height and a thick border around it:

The example shown above is rendered in Firefox 3.6.13 using the following source code:

<ul style="height: 90px; border: 5px solid black; padding: 0;">
    <li style="height: 25%; background: red;">
    <li style="height: 25%; background: blue;">
    <li style="height: 25%; background: yellow;">
    <li style="height: 25%; background: green;">
</ul>

While this works perfectly in Firefox, Safari or Chrome might introduce a small white gap between rows due to pixel rounding. This issue arises because non-integer pixel heights are not handled consistently across browsers.

To resolve this discrepancy, we need a flexible solution that adjusts based on varying content lengths. While setting precise pixel values manually could work in static scenarios, a dynamic solution is crucial for database-driven content.

One approach involves JavaScript calculations to ensure integer pixel row heights, which can be set onload. However, if you prefer a purely CSS-based solution, consider exploring alternative methods to address this rendering inconsistency. Do you have any ideas?

Answer №1

Here is a Javascript solution to tackle the problem at hand, as promised. While I am still on the lookout for a simple CSS-based fix, this response could be beneficial for others looking to complete their task.

In order for the script to work seamlessly, two variables must be declared initially: list should reference the DOM element of the container (such as <ul>), and items should indicate the collection of items within this list (like <li>).

The approach involves dynamically assigning an explicit height in pixels to each item, ensuring that the total height matches the container's height while keeping deviations in height between items minimal. This is achieved by iterating over the items, calculating an integral height for each one by dividing the remaining available space by the number of items yet to have a definite height set.

var spaceRemaining = list.clientHeight;
var itemsRemaining = items.length;

while (itemsRemaining > 0) {
    var itemHeight = Math.round(spaceRemaining / itemsRemaining);
    items[itemsRemaining - 1].style.height = itemHeight;
    spaceRemaining -= itemHeight;
    itemsRemaining -= 1;
}

For those who prefer concise code over readability, here's a succinct version of the same script:

for (var space = list.clientHeight, i = items.length; i; i--) {
    space -= items[i-1].style.height = Math.round(space / i);
}

Answer №2

Attempt to eliminate all line breaks between <li> elements. For example

<ul><li></li><li></li></ul>

Occasionally this issue arises, but I'm uncertain if it will resolve your current situation ;) Give it a shot ;)

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

Ways to customize the background color of selected items in ion-list on Ionic

I am working on an Ionic project and I have a list of items. I am trying to change the background color of the pressed item. Can someone help me with this? index.html <ion-list> <ion-item ng-repeat="item in familleItems"> <div ng- ...

Laravel application faces issues with URL rewriting generating incorrect URLs in compiled CSS files

Having some trouble compiling Font Awesome SCSS files in my Laravel application. I installed Font Awesome using NPM, and the compiled CSS is stored in the 'public/css/' folder while a 'public/fonts/' folder was also created. However, th ...

Using CSS transform to enhance Flash content

I am currently working on a web application that is contained within an iframe. The iframe has been scaled using -webkit-transform:scale(0.8), which is functioning well. However, I am encountering an issue with the flash audio recorder within the iframe no ...

Styled Components do not have the ability to define :hover states

export const WatchVideoButtonWrapper = styled.div` position: absolute; bottom: 80px; right: 33px; background-color: ${(props) => props.bgColor}; color: ${(props) => props.color}; border-radius: 100px; transition: all 0.1s; ...

When an li element is styled with a width of 50% and floated to the left, it does not display the bullet points

When attempting to create a 2-column list, I implemented the following CSS: ul { overflow: hidden; } ul li { float: left; width: 50%; } However, I noticed that when I have 2 items in the list, the one on the right displays a list bullet while th ...

Tips for creating an HTML page with the dimensions of an A4 paper sheet?

My goal is to display the HTML page in a browser while containing the content within the dimensions of an A4 size page. Additionally, when printed, the HTML page should be formatted to fit onto A4-sized paper pages. <div classNa ...

Adjusting Chart.js line graph alignment to the left

I'm curious about why my chart is not aligned to the left and how I can fix this issue. Here is the code snippet I am working with: var data = { labels: ["ID"] , datasets: [ { label: "Sensor 1" , data: [{ ...

What are the steps to design a curved gauge with a linear-gradient background?

Looking to create a fully responsive gauge using only CSS, ranging from 0-100% with a gradient color transition from green to red. After encountering issues with existing examples, I conducted tests and ultimately developed a solution that somewhat meets t ...

Can a javascript code for "Infinite Scroll" be created to manage the back button?

Head over to this website: Experiment with the infinite scroll feature. You may notice that when you click a link and then press "back", there are some glitches. Therefore, I am considering developing my own version of an Infinite Scroll functionality. ...

What is the best way to create separate positions for items within a single div?

https://i.sstatic.net/FQRY4.jpgAfter looping through various names and accessing them from a single div using {{item}}, I encountered an issue. All the names are within one parent element. This is the code snippet: <div :style="image" cl ...

Animation showing on the progress bar is not correctly halted

I am encountering a problem with handling an animation of a progress bar in my code. The issue arises when I pause the animation, as it seems to slightly backtrack instead of pausing at the correct position upon clicking a button. Can someone help identify ...

Upgrade the arrow accordion in bootstrap by incorporating images instead

I have implemented a Bootstrap accordion with a toggle arrow. Here is an example: http://jsfiddle.net/zessx/r6eaw/12/ My question is, if I want to change the arrow with an image, what do I need to edit? Or how can I implement it? This is the image I want ...

Issue with Ng-style not functioning properly when setting background color

I am struggling to set the background of an element using a configuration object with ng-style. For some unknown reason, I can't seem to make it work and I'm finding it really perplexing. The element I'm attempting to configure: <div id ...

Adjust the size of a Highcharts chart before printing

I'm facing an issue with a chart that doesn't have a specified height or width. My goal is to print the graph in a taller and larger size when I click on the print button. I attempted to use setSize() function, but since there are no original di ...

Scale transformation causing text display problem in Firefox

Using css-transforms for scaling text on hover to another size is working smoothly in all browsers, except for Firefox. The font in the scaled element appears slightly unsharp initially, then sharpens after a few milliseconds. You can test and see this is ...

Organize objects neatly in a grid formation

I have a .test div with grid-template-columns: auto auto auto;. The column width is set to vary based on the element width, and I also used justify-content: start; to align the columns to the left. I chose to use auto instead of 1fr to prevent the columns ...

I'm struggling to adjust the height of a div based on whether a list item within it contains a nested unordered

I have been working on a horizontal menu that is functioning well for me. However, according to the design requirements, I need to adjust the height of <div id="nav-subMenu"></div> if the main/parent menu li does not have any submenus or ul. Th ...

Tips for positioning a highcharts pie chart and legend in the middle of a page

I'm struggling to center my highchart data in a node/react single page application. Currently, it appears off-center like this: https://i.stack.imgur.com/ccR6N.png The chart is floating to the left and I would like to have everything centered within ...

Unexplainable space or padding issue detected in OwlCarousel grid gallery

There seems to be an unusual gap or margin at the bottom of each row section in this portfolio grid gallery that's running in OwlCarousel. You can view an example here. https://i.stack.imgur.com/NHOBd.png I've spent a lot of time trying to solv ...

Allowing horizontal scrolling in a table cell set to full width

I'm attempting to achieve the desired outcome by utilizing the code provided at What I'd like to know is why the scrolling function isn't working as expected. Instead of scrolling, it simply expands the table. To see the difference, try run ...