What causes the inconsistency in width distribution among flex children when the flex grow property is set to 1 alongside text content?

Why do the elements one, two, and damn not take up equal space, as they all have flex: 1? I want them to have equal widths based on the parent's width.

How can I adjust it so that the element with class damn takes up less space than the other two?

.wrap {
  display: flex;
  background: #ccc;
}

.one {
  flex: 1;
  background: red;
}

.two {
  flex: 1;
  background: yellow;
}

.damn {
  flex: 1;
  background: blue;
}
<div class='wrap'>
  <jjwui><t/adsjjshv>
  </div>
</div>

Answer №1

From my interpretation of the question, it seems you want to know why the elements one and two do not occupy an equal amount of space as the element with the class .damn.

If I am correct in understanding that question, let's consider the following demonstration:

// Here we define a named function using Arrow syntax, which
// accepts a single argument:
const analyze = (element) => {
    // Inside this function, we declare some variables using object destructuring
    let {
      width,
      height,
      flexGrow,
      flexShrink,
      flexBasis
    } = window.getComputedStyle(element, null),
      tempElement = document.createElement('div');
    
    tempElement.innerHTML = generateTemplate({
      width,
      height,
      flexGrow,
      flexShrink,
      flexBasis
    });
    
    element.prepend(tempElement.querySelector('ol'));
  },
  
  // Another named function utilizing Arrow syntax:
  generateTemplate = (data = {}) => {
    return `
<ol class="analysis-report" style="--verticalAdjustment: ${data.height}">
  <li class="height">height: <var>${data.height}</var></li>
  <li class="width">width: <var>${data.width}</var></li>
  <li class="flexGrow">flex-grow: <var>${data.flexGrow}</var></li>
  <li class="flexShrink">flex-shrink: <var>${data.flexShrink}</var></li>
  <li class="flexBasis">flex-basis: <var>${data.flexBasis}</var></li>
</ol>`
  }

// Selecting all div elements inside the .wrap container,
// Iterating over them using NodeList.prototype.forEach() 
// and calling the analyze() function for each element:
document.querySelectorAll('.wrap > div').forEach(analyze);

To see the demonstration in action, you can check out the JS Fiddle demo.

The discrepancy in the sizing might be due to the content layout calculations performed by the browser. In cases where there is messy HTML structure within the element with the class .damn, the ability of the browser to break lines for proper formatting is limited, resulting in longer unbreakable lines dictating the overall width of the element.

However, organizing the HTML content within the .damn element for better readability and allowing new-line breaks improves the display outcome significantly. You can achieve a more balanced sizing by adjusting the flex properties accordingly. For example, setting lower values for flex on the .damn element compared to the others:

const analyze = (element) => {
    let {
      width,
      height,
      flexGrow,
      flexShrink,
      flexBasis
    } = window.getComputedStyle(element, null),
      tempElement = document.createElement('div');
    
    tempElement.innerHTML = generateTemplate({
      width,
      height,
      flexGrow,
      flexShrink,
      flexBasis
    });
    
    element.prepend(tempElement.querySelector('ol'));
  },
  
  generateTemplate = (data = {}) => {
    return `
<ol class="analysis-report" style="--verticalAdjustment: ${data.height}">
  <li class="height">height: <var>${data.height}</var></li>
  <li class="width">width: <var>${data.width}</var></li>
  <li class="flexGrow">flex-grow: <var>${data.flexGrow}</var></li>
  <li class="flexShrink">flex-shrink: <var>${data.flexShrink}</var></li>
  <li class="flexBasis">flex-basis: <var>${data.flexBasis}</var></li>
</ol>`
  }

// Adjusting the flex properties to control the sizes of the elements
document.querySelectorAll('.wrap > div').forEach(analyze);

A practice worth considering is maintaining readable code for better troubleshooting and clarity. While in some instances, minification may be necessary, ensuring your code remains legible is essential for effective development.

For further information, refer to these resources:

References:

Answer №2

It is not recommended to use the <div> tag as an empty tag.

.wrap {
display: flex;
background: #ccc;
}

.one {
flex: 1;
background: red;
}

.two {
flex: 1;
background: yellow;
}

.damn {
flex: 1;
background: blue;
}
<div class='wrap'>
  <div class='one'></div>
  <div class='two'></div>
  <div class='damn'>
    Lorem ipsum dolor sit amet hello world, Lorem ipsum dolor sit amet hello world.
  </div>
</div>

Answer №3

Explanation

The div tag is not a self-closed tag like an input. To make it work, you need to change from <div /> to <div></div>.

<div class='wrap'>
  <div class='one'></div>
  <div class='two'></div>
...

.wrap {
  display: flex;

  background: #ccc;
}

.one {
flex: 1;
  background: red;
}

.two {
flex: 1;
  background: yellow;
}

.damn {
flex: 1;
  background: blue;
}
<div class='wrap'>
  <div class='one'></div>
  <div class='two'></div>
  <div class='damn'>
    Lorem ipsum dolor sit amet hello world, Lorem ipsum dolor sit amet hello world.
  </div>
</div>

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

Is it possible to adjust the vertical background-position independently?

While creating a navigation bar using the <ul> element, I have come up with the following CSS code: .nav { list-style: none; background: url(/images/nav.png) no-repeat; width: 666px; height: 60px; } .nav li { font-size: 0px; backgr ...

A helpful guide to adjusting the cursor placement within a contenteditable div using React

I am developing a custom text editor using a contenteditable div. Each time a user modifies the text inside it, I aim to enclose all the new text with a strong element and update the div's innerHTML accordingly. Here is what I have attempted (utilizi ...

Tips for utilizing angular ui.layout in column mode: Implementing a bottom-aligned element

Recently, I began utilizing angular ui-layout to enable pane splitting within a user interface. I am attempting to design a sidebar that features a blue element at the bottom. Is there a way to manipulate the ui-layout directive to accomplish this? I exp ...

Remove the bootstrap styling from a section of the webpage

I am in the process of setting up a preview box for an HTML editor on one of my pages. I created a basic <div id="preview"></div> style container where I occasionally input my HTML source, which is working adequately. The issue arises when Boo ...

What is the best way to ensure that all the responses to questions in HTML yield a singular outcome?

Can you help me figure out how to link all the answers to questions or user preferences to one ultimate result? I love how Craigslist guides users through their preferences to lead them to one specific outcome. For example, how can I connect these two ques ...

Ways to center elements horizontally without relying on Flexbox layout?

Is there a way to arrange the web elements side by side without relying on Flexbox? Although an effective tool, Flexbox does not function properly with IE 9 or 10. I am aiming for the text inside the link to be displayed immediately next to the images. The ...

Is it possible to customize the Menu hover effect in Element Plus and Vue?

Hello everyone, I'm a beginner with Vue, HTML, CSS, and Element Plus. I am trying to customize a Side Bar Menu with my own hover effect, but it doesn't seem to be working. Whenever I change the background color of the el-menu element, the hover e ...

Show a notification when utilizing AJAX requests

I consist of two separate files: one written in PHP and the other one in JavaScript and HTML. PHP file : <?php session_start(); //start session $_SESSION['data'] = "The content should be displayed as alert in the JS file"; JS/HTML File: & ...

What is the best way to extract text from a dynamically changing element using jQuery?

I've been struggling with a coding issue. Despite trying numerous approaches, I keep encountering the same problem where every new button I add ends up having the same text or, alternatively, nothing seems to work as expected. $j serves as my variabl ...

Issues with tabs functionality in Bootstrap version 4.3.1, unlike the smooth operation in v4.1.0

I encountered an interesting situation recently. After spending almost 3 hours troubleshooting my code, I discovered that it functions perfectly on Bootstrap v4.1.0 but fails on the latest version, v4.3.1. Working JSFiddle with Bootstrap v4.1.0: https://j ...

Navigating through a predetermined list of HTML pages with next and previous options

Hey there, I'm in a bit of a quandary at the moment. I've been searching on Google for quite some time now, but unfortunately, I can't seem to find what I'm looking for. Hopefully, you guys can lend me a hand. What I'm trying to d ...

Problem encountered when trying to create a fixed position Sticky Div

I've attempted to create a sticky DIV using the code below, but it's not behaving as anticipated. The DIV sticks when I scroll down, but it overlaps with the website Header and Footer. How can I fix this issue using CSS/JS? Any assistance would b ...

I require a way to decelerate the speed of the roulette wheel's rotation

For my assignment, I'm tasked with creating a roulette spin wheel code in JavaScript without using any plugins. I need to incorporate some conditions before executing the code, particularly for slowing down the speed of the roulette spin. Additionally ...

What is the method to activate sequential selection through JSON response?

I just started exploring angularjs and I'm interested in selecting values step by step. But first... Here's the JSON response I received: [ { "countryname": "India", "states": [ { "statename": "Karnataka", ...

What is the button that switches the bootstrap modal?

With my bootstrap modal form, I have multiple buttons that trigger it as shown below: <a href="javascript:void(0)" data-toggle="modal" data-target="#specialoffer"> <button class="green full" id="button1">Ask Question</button> </a& ...

Tips for presenting styled HTML content within a dynamic list using HTML and JavaScript

Is there a way to display HTML formatted text within a dynamic list in HTML? I've tried implementing it, but the tags are being displayed instead of the formatted text. Here's an example of the code: <!DOCTYPE html> <html> <body> ...

Manage the element that should receive focus() after tab is pressed from an input field

On my webpage, there is a variety of elements such as inputs and anchors. I need to specify which input field the browser should move focus to when I press the tab key while on an input. Currently, pressing tab from one specific input takes me to a menu i ...

Utilizing the map function to display elements from a sub array

I'm struggling to print out the comments using the map function in this code: class Postcomment2 extends React.Component { uploadcomment = () => { return this.props.post.comments.map((comment) => { return <div>{comment["comment"]}< ...

The ng-model remains empty even after the $parent has been defined

I've encountered an issue where assigning ng-model to a text area and an input does not update the models. It is mentioned that this could be due to using ng-if causing a different scope, and I should use $parent, but even that solution is not working ...

Is there a way to alter the color of options within a select tag when hovering the mouse over them

After searching through multiple websites, I couldn't find a solution on how to change the option background color on hover from blue to green. The screenshot provided below illustrates what I am requesting for in a clearer manner. https://i.sstatic. ...