CSS failing to accurately calculate width when children have percentage values assigned

This CSS quirk is quite interesting...

An inline-block container will correctly calculate width when using units like px, vw, em, etc. But it behaves differently when using a percentage-based measurement.

Percentage Example: https://i.sstatic.net/saI0M.jpg Pixels Example (which is correct): https://i.sstatic.net/MCWey.jpg

Here's the HTML:

    .clip{
      width: 100%; overflow:hidden;
      position:relative;
    }
    .show-width-con{
      min-width: 100%; 
      display:inline-block;
      white-space:nowrap;
    }
    .element-perc{
      width:24%;
      display:inline-block;
      vertical-align: top;
      position: relative;
    }
    
    .element-px{
      
      width:300px;
      display:inline-block;
      vertical-align: top;
      position: relative;
    }
  <div class="clip">
      <div class="show-width-con">
        <div class="element-perc">25%</div>
        <div class="element-perc">25%</div>
        <div class="element-perc">25%</div>
        <div class="element-perc">25%</div>
        <div class="element-perc">25%</div>
        <div class="element-perc">25%</div>
      </div>
    </div>
    
    <br><br>
    
    <div class="clip">
      <div class="show-width-con">
        <div class="element-px">300px</div>
        <div class="element-px">300px</div>
        <div class="element-px">300px</div>
        <div class="element-px">300px</div>
        <div class="element-px">300px</div>
        <div class="element-px">300px</div>
      </div>
    </div>

Check out the code snippet on Codepen: https://codepen.io/digitalzoomstudio/pen/BYWEoG

Answer №1

When considering the 25% width of a container, it's important to remember that it is based on the entirety of the window. For example, if your window is 1200px wide, then 25% of that would be 300px. When multiplied by the number of divs you have (6), it results in a total width of 1800px. This explains why the first parent container measures 1200px and the second measures 1800px.

The 100% width attribute pertains to the container itself, not the content it holds. By removing the min-width from .show-width-con, you will notice that the 25% containers have no width because 25% of nothing is nothing. With a min-width of 100%, the first container gets a width of 1200px (equivalent to 100% of the window), making the 25% containers 300px wide. The overflow may be clipped, but it does not alter the width of the container.

Keep in mind that the min-width sets the minimum width, not the total width. Therefore, the container accommodating the 300px width will expand up to its maximum size of 1800px (300px multiplied by 6). Converting min-width to width will show that this container also measures 1200px, again reflecting 100% of the window.

Alternatively, consider this: If the parent container were actually 1800px wide, then 300px would not constitute 25% of its width; instead, 450px would be the correct value. This discrepancy would lead to further inaccuracies in calculations. Regardless of the window size, 300px remains 300px.

Answer №2

.clip{
  width: 100%;
  max-width: 100%;
  position:relative;
}

.show-width-con {
  font-size: 0;
  min-width: 100%; 
  max-width: 100%;
  display:inline-block;
}

.element-perc {
  font-size: 16px;
  width:25%;
  display:inline-block;
  vertical-align: top;
  position: relative;
}

.element-px{
  font-size: 16px;
  width:300px;
  display:inline-block;
  vertical-align: top;
  position: relative;
}
<div class="clip">
  <div class="show-width-con">
    <div class="element-perc">25%</div>
    <div class="element-perc">25%</div>
    <div class="element-perc">25%</div>
    <div class="element-perc">25%</div>
    <div class="element-perc">25%</div>
    <div class="element-perc">25%</div>
  </div>
</div>

<br><br>

<div class="clip">
  <div class="show-width-con">
    <div class="element-px">300px</div>
    <div class="element-px">300px</div>
    <div class="element-px">300px</div>
    <div class="element-px">300px</div>
    <div class="element-px">300px</div>
    <div class="element-px">300px</div>
  </div>
</div>

Eliminating gaps between inline-block elements can be achieved by using html comments or by adjusting font sizes within the elements.

For more complex layouts, consider using float grids, flexbox, or css grid for better browser support and alignment capabilities.

Flexbox or css grid are recommended for achieving vertical alignment in layouts.

References:

css-tricks

treehouse-post

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

changing the value of a text input based on the selected option in a dropdown using ajax

I attempted to update the text input value with data from the database after selecting an option from the dropdown list. However, I encountered an issue where the data is not populating the text input field. <?php //Including the database configuration ...

Having difficulties adjusting the margin for a JSX element directly within the code

I'm struggling with giving a margin style inline to a JSX element. Here's the code snippet that I'm having trouble with: <Nunito20 style={{color: frenchGray, margin: 20 0 3 0;}}>Full Name</Nunito20> Unfortunately, this is throw ...

Preventing Text Chaos in CSS Layouts: Tips and Tricks

I'm facing an issue with the alignment on this page: . When the page is resized, some of the text links are too long and causing a problem with the layout of the stacked images. How can I fix this? Here is the HTML & CSS code for reference: CSS: #b ...

Center a single div vertically within a parent div by utilizing a fluid layout

Attempting to align text elements within a responsive layout presents challenges due to the fluid nature of <div> sizes. I recently discovered a fantastic method for horizontally and vertically centering a child <div> inside its parent <div ...

Incorporate my personal design flair when utilizing third-party React.js component libraries

Incorporating Material UI as a component library in my React project has been beneficial. However, I am facing a challenge where the inline styling provided by Material UI clashes with my existing custom styles that I have developed over time. Is there a ...

Methods for encoding and decoding special characters using either JavaScript or jQuery

I am looking for a solution to encode and decode various special characters using JavaScript or jQuery... ~!@#$%^&*()_+|}{:"?><,./';[]\=-` I attempted to encode them using the following code snippet... var cT = encodeURI(oM); // ...

Positioning of buttons within a div

I am currently designing an inspiration post style: https://i.stack.imgur.com/I5J0H.png However, I am encountering some challenges while creating it: The buttons are not rounded when the window size is changed Social icons are not being displayed I am ...

Ways to streamline a form containing several duplicate rows and make it more user-friendly

Looking for some advice on implementing a "working hours" module. Just need something simple like: Monday: 10:00 - 18:00 ... Saturday: 11:00-16:00 with some additional info. I'm currently attempting to... <form id="working_hours"> <s ...

Organizing communications in NodeJS messaging application

My latest project involves creating a chat room using NodeJS and socket.io which allows multiple users to connect with unique usernames. Everything is running smoothly, except for one minor issue. I want the messages sent by me to appear in a different co ...

What is the proper way to utilize CSS animation delays in order to design a collapsible HTML container?

I'm trying to implement responsive CSS animation delay to create an accordion effect when a user clicks on an arrow associated with a table, all without using JavaScript and only utilizing HTML/CSS. Check out the mobile view in action here: https://w ...

Populate div with straight lines running vertically or horizontally

I'm wondering how to create vertical or horizontal lines inside a div. I tried this in the past but lost the code, and searching for "fill div with lines" isn't giving me any relevant results. Here's an image to illustrate what I'm try ...

Styling div elements within other div elements using CSS

I am currently working on creating a layout with three divs, each containing an image. The challenge is to set the height of the first div (top) to 10% of the screen size, the second (middle) to 60%, and the third (bottom) to 30%. I want these divs to main ...

Looking to modify the HTML layout in order to be compatible with a specific script

Utilizing a form validation script with required:true data-validation will stop the form from submitting and highlight invalid fields in red by adding "has-error" to the parent container when the user submits the form. In the code snippet below, "has-erro ...

Jquery not functioning properly for show and hide feature

I'm new to using Jquery and JqueryUI. I have a div named front, which I want to initially display on window load and then hide it by sliding after a delay of 5500 milliseconds. However, I'm encountering errors in the jquery.min.js file. The HTML ...

Is it possible to use D3 for DOM manipulation instead of jQuery?

After experimenting with d3 recently, I noticed some similarities with jquery. Is it feasible to substitute d3 for jquery in terms of general dom management? This isn't a comparison question per se, but I'd appreciate insights on when it might b ...

Having trouble adding animation to button element following the application of :after pseudo-element styling

I've been grappling with pseudo elements, but I just can't seem to make a simple button animation work using them. My goal is to have a panel move from bottom to top on hover. Similar to the button found on this page (1st row, 2nd button). From ...

Ways to display a specific section on an HTML page using AngularJS

Main page content <div class="row"> <div class="col-md-3"> link 1 link 2 link 3 . . . </div> </div> <div class="col-md-9"> <div ng-view></div> </div& ...

What steps can I take to use CSS to disable a webpage?

Is there a way to create a disabled web page using CSS where users cannot click on any content and only view the content below the screen? ...

Is there a way to conceal a component using Twitter Bootstrap while having the ability to reveal it with the help of

Suppose I generate an HTML element in the following manner, <div id="unique-div" class="concealed">Hello, TB3</div> <div id="unique-div" class="hide-me">Greetings, TB4</div> <div id="u ...

Concentrate on a specific component within an overlay using jQuery

How can I focus on a specific area within an overlay when adding an item to the cart? I want to make the rest of the overlay darker and the targeted area more visible. See a quick mockup here: https://i.sstatic.net/UpJuc.png Here's the HTML code: & ...