What is the correct way to accurately determine the width of a block being displayed with the flex-direction:column property?

For instance:

HTML

console.log($('.container').width()); // 600px as we defined in css.
console.log($('.list').width()); // 600px

console.log($('.box').eq('-1').position().left + $('.box').outerWidth());
body{padding:0;margin:0;}
.container {
  width: 600px;
  background:#E1BEE7;
}

.list {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height:120px;
  background:#FFCDD2;
}

.box {
  margin:10px;
  flex-shrink:0;
  flex-grow:0;
  flex-basis:auto;
  width: 100px;
  height: 100px;
  text-align:center;
  line-height:100px;
  background: #F44336;
  color:#FFF;
  font-size:2rem;
}

.result{
  padding:1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <div class="list">
    <div class="box">1</div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
    <div class="box">5</div>
    <div class="box">6</div>
    <div class="box">7</div>
    <div class="box">8</div>
    <div class="box">9</div>
    <div class="box">10</div>
  </div>
</div>

There are 10 boxes, each with a width of 100px. The actual width of the .list element should be 1000px, not 600px.

I attempted to use the following method to obtain the actual width of the list: The left position of the last child element and its outerWidth.

console.log($('.box').eq('-1').position().left + $('.box').outerWidth());

What I'm curious about is if there is a more efficient way to get the actual width of this type of flexbox element? Are there any better built-in JavaScript or jQuery methods for this?

Answer №1

I'm looking for the value of el.scrollWidth.

Answer №2

If you're looking for a way to calculate the total width of elements within a div using JavaScript and jQuery, here's a solution that might be helpful:

var totalWidth = 0;
$('.box').each(function() {
  totalWidth += $(this).width();
});

$('#msg').html(
  "<p>totalWidth: " + totalWidth + "</p>"
);

You can see a live example here.

If you prefer to do it without jQuery, you can use this alternative method:

var totalWidth = 0;

var cont = document.getElementsByClassName('box');
for (var i = 0, len = cont.length; i < len; i++) {
    totalWidth += cont[i].offsetWidth;
}

document.getElementById('msg').innerHTML = "<p>totalWidth: " + totalWidth + "</p>";

For a native JavaScript implementation, you can check out this example.

Answer №3

After some exploration, it seems that the scrollWidth property will provide the dimension you are seeking. The reason why outerWidth is not giving the total width of the internal elements is because your .list element has a width of 600px. This causes the extra content to overflow its container, allowing it to be visible outside of the .list.

You can verify this by changing the overflow property to hidden on the .list:

body { padding: 0; margin: 0; }
.container {
  width: 600px;
}

.list {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 120px;
  background: #FFCDD2;
  overflow: hidden;
}

.box {
  margin: 10px;
  flex-shrink: 0;
  flex-grow: 0;
  flex-basis: auto;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  background: #F44336;
  color: #FFF;
  font-size: 2rem;
}

.result {
  padding: 1rem;
}
<div class="container">
  <div class="list">
    <div class="box">1</div>
… (Remaining snippet code)
  </div>
</div>

When you try this out, you'll see that the .list element hides the excess boxes.

This explanation should clarify what is happening and also offer a solution to the issue at hand. Best of luck!

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 is the best way to set up an anchor element to execute a JavaScript function when clicked on the left, but open a new page when clicked in

One feature I've come across on certain websites, like the Jira site, is quite interesting. For instance, if we take a look at the timeline page with the following URL - When you click on the name of an issue (which is an anchor element), it triggers ...

Having difficulty displaying Laravel API data with Relationship in Vue Js

Working on a project that involves Laravel 10 API and Vue.js 3 frontend In my EmployeeController.php file, I have three models: Employee, Title, and Salary. The Employee model has a many-to-many relationship with the Salary and Title models, while the Sal ...

[Web Development]:

Having an issue with my HTML file where a JavaScript function named "CheckCaptcha" is not being executed when an image is clicked. I've been working on the code for hours, trying different tweaks and modifications, but it still can't seem to find ...

Refresh the copyright year by syncing with a time server

Not long ago, I found myself needing to update the copyright year on a website. Instead of using JavaScript to get the year from the system time, I began wondering if there was a way to utilize an internet time server for this purpose. I believe that util ...

Comparing Flash and jQuery for RIAs development: Which tool reigns supreme and why?

Could someone clarify which technology is more suitable for developing rich internet applications: Flash or jQuery? Consider aspects like pros and cons, time, cost, and different scenarios. Please provide detailed explanations as it can be quite confusin ...

To enhance your React Class Component, make sure to utilize the withStyles feature when

This particular component is not set as a default export component. I am attempting to apply some styles to it but struggling to figure out how to encapsulate it in an HOC. Hence, the current issue where it does not recognize the classes variable. import ...

Struggling to change the div content with ajax response transmitted through php

I would like to apologize in advance if this question has already been addressed elsewhere. After conducting a search, I came across several relevant posts that have guided me to this point. Below is the form snippet containing 1 input box, a button, and ...

Maintain the state of the previous page in Vue to ensure continuity

Currently in the process of creating a small PWA to simulate an Android app, I have discovered Vuejs. However, I encountered an issue that has proven difficult to resolve. While scrolling through lists on the homepage for movies, TV shows, or news, clicki ...

choosing concealed div

Struggling to target the span element within the initial item of an unsorted list, but struggling with getting the DOM structure right. <li class="chapterItem"> <a href="http://www.neuromanga.com/mangaReader.php?chapterNo=12&amp;#page ...

Is there a way to navigate through div text within a stationary container?

My current challenge involves a container that contains an overflow of text, but I desire for the container to remain fixed. The dilemma arises when the text spills out from both the top and bottom edges of the container. Instead of using scroll bars withi ...

I'm curious, in which environment does SvelteKit, Next.js, and Nuxt.js code execute? Also, is it possible to create HTTP request handlers within

My experience with using SvelteKit in my personal projects has been quite enjoyable. However, coming from a background of working with frameworks like Next.js and Nuxt.js, I often find myself confused about where the code I write actually runs. In my day ...

Using Google Fonts in a Typescript React application with JSS: A step-by-step guide

How can I add Google fonts to my JSS for use in styling? const styles = ({palette, typography}: Theme) => createStyles({ time: { flexBasis: '10%', flexShrink: 0, fontSize: typography.pxToRem(20) }, guestname: ...

Enhancing React Functionality: Increasing React State Following an If Statement

Whenever I click on the start/stop button, it triggers the handlePlay function. This function then proceeds to initiate the playBeat function. In an ideal scenario, the play beat function should continuously display 1222122212221222... until I press the st ...

Identifying geometric coordinates within Canvas

Currently, I am adding drag and drop functionality to my HTML5 Canvas application. I have encountered a challenge in determining how to detect if the shape being clicked on is not a rectangle or square. For instance, within my 'mousedown' event h ...

Navigating within fixed-positioned divs

I'm attempting to create something similar to the layout seen on: The desired effect is to have fixed content on the right side, with only the left side scrolling up to a certain point before the entire page scrolls normally. However, in my implement ...

Utilizing JavaScript in AJAX Responses

Can I include JavaScript in an AJAX response and run it, or should I only use JSON or plain HTML for a more elegant solution? I'm trying to figure out the best way to handle AJAX requests that involve inserting HTML or running JavaScript based on user ...

What is the method to switch between radio buttons on a webpage?

Here is an example of HTML code: <input type="radio" name="rad" id="Radio0" checked="checked" /> <input type="radio" name="rad" id="Radio1" /> <input type="radio" name="rad" id="Radio2" /> <input type="radio" name="rad" id="Radio4" /& ...

Methods for applying a style property to a div element with JavaScriptExecutor in Selenium utilizing C#

I have been attempting to change the style of a div element using JavascriptExecutor in C#, but so far, nothing has happened. IJavaScriptExecutor js = (IJavaScriptExecutor)driver; IWebElement element = driver.FindElement(By.XPath("//div[contains(@class, ...

Utilize Vue.js methods to reverse the string within a paragraph using the appropriate function

Hello everyone, I've been attempting to implement a function to reverse a string within a paragraph text in vue.js. I've created a method called reverseword to reverse the words and added it to a card using :rule="reverseword()", but un ...

What is AngularJS global data binding?

My template has a dynamic title that is inserted using the following code: <title>{{title}}</title> For each of my pages/routes, I use a different controller where I define the title like this: BackyApp.controller('HomeController', ...