Observing changes in the dimensions of flex children using MutationObserver

Considering the following structure of the Document Object Model...

<div id="outer-container">
  <div class="side-panel"><div width="200px"/></div>
  <div id="content"><!-- some content --></div>
  <div class="side-panel"><div width="100px"/></div>
</div>

And with these specified CSS rules...

#outer-container {
  display: 'flex';
  align-items: 'stretch';
  width: '100vw';
  height: '100vh';
}

.side-panel {
  flex-shrink: 0;
}

#content {
  display: 'flex';
  flex-direction: 'column';
  align-items: 'stretch';
  flexGrow: 1;
}

Is there a way to monitor changes in the width/height of #content?

Typically, this involves observing mutations in the style attribute and verifying the element's dimensions when the style is altered. However, as it is a child within a flex container, checking the width/height attributes reveals them undefined.

Mutations to the size of #content do not trigger events from my MutationObserver (configured with

{attributes: true, attributeFilter: ['style']}
) as expected.

The objective is to convert the side panels into drawers once the width of #content falls below a certain limit. I am using React, but this issue seems to be more JavaScript/html-related.

Any assistance would be greatly appreciated!

PS: I attempted setting flex-basis on #content to the predefined threshold, with no success. Should I define a specific width instead of utilizing flex-basis? Uncertain if this might lead to unintended flex behavior.

Answer №1

To determine the dimensions of an element, you have a few options available to you. You can use properties like offsetWidth/offsetHeight, the method getBoundingClientRect(), or the method getComputedStyle() within a function such as checkWidth(). Make sure to call this function whenever events or functions alter the dimensions of your element.

An example would be using a resize event to trigger changes in your element's dimensions and then running the function when that event occurs.


To see this concept in action, run the following Code Snippet and then either resize your browser or click the button for a practical demonstration:

/* JavaScript */

function checkWidth(){
  let e = document.getElementById("content");
  let widthA = window.getComputedStyle(e).width;
  let widthB = e.getBoundingClientRect().width;
  let widthC = e.offsetWidth;

  console.log("getComputedStyle: " + widthA);
  console.log("getBoundingClientRect: " + widthB);
  console.log("offsetWidth: " + widthC);
};

window.addEventListener("resize", checkWidth); // Include checkWidth() since "resize" affects element's dimensions

function editContent(){
  let e = document.getElementById("content");
  e.style.width = "300px";
  
  checkWidth(); // Run checkWidth() after editContent() alters element's dimensions
}

document.getElementById("btn").addEventListener("click", editContent);
/* CSS */

#outer-container {
  display: flex;
  align-items: stretch;
  width: 100vw;
  height: 100vh;
}

.side-panel {
  flex-shrink: 0;
}

#content {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  flex-grow: 1;
}
<!-- HTML -->

<button id="btn">Click Me</button>
<hr/>
<div id="outer-container">
  <div class="side-panel">
    <div style="width: 200px">Left</div>
  </div>
  <div id="content">Middle</div>
  <div class="side-panel">
    <div style="width: 100px">Right</div>
  </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

When adding margin-left and margin-right, images do not appear in their designated positions

I have a chart displaying images, which are showing up correctly. However, I am facing an issue when I try to add some spacing to the chart by using margin-left and margin-right. Here is the CSS code I included: #chart1 { margin: 0 auto; ...

What could be causing the CSS and HTML connection to fail?

I am currently working with Flask on the Atom editor to build a website. Despite specifying the correct path for the CSS file in the link, every time I load the page, it appears without any styling. I have attempted changing the paths multiple times with n ...

Creating consistent image placement across all divs: a step-by-step guide

html { font-family: 'Open Sans', sans-serif; } body {margin: 0; padding: 0; } #wrapper { padding-left:50px; padding-top:30px; } #third, fifth { background-color:#E8E8E8 ; } img[src^="my_menu.png"] { z-index:10; } #s ...

Customize the website's CSS for optimal viewing on an iPad

I have a website with two CSS files: one for viewing the site on a desktop screen and the other for viewing it on an iPad screen. Despite having the same HTML code, is there a way to detect the iPad device and force it to use the appropriate CSS file? Tha ...

Rotate Text in HTML <thead> Tag

I need assistance with rotating a table header. https://i.stack.imgur.com/hcvxx.png The HTML th elements within the thead section are described as follows: <th> <span class="rotate-all">Period</span> </th> <th> < ...

Examining pseudo-elements on Internet Explorer

Recently, I encountered an issue with a pseudo-element: input[type=radio].selected::before Surprisingly, in Internet Explorer, the pseudo-element wasn't visible at all. This prompted me to investigate further. Upon inspecting the selector (imagi ...

Exploring the world of JQuery Ajax selectors

I am attempting to create a comment system similar to the one found at . I have the AJAX code below, but I am having trouble uniquely selecting text areas for each post. The issue is that the number of posts can vary, so it's important that each post ...

How to properly center and align the width of a figcaption element within an image placed in a figure element

I've been struggling for two days now trying to fix an issue with the alignment of images and captions on my Django application. In my app, users can upload images, and I'm using figure and figcaption tags to display the image with a caption. Ho ...

What is the best way to prevent right floated DIVs from interfering with each other's positioning, specifically within a specified space?

Despite feeling like this question may have been asked numerous times before, I've searched high and low for an answer to no avail - both here and on Google. My HTML page has a maximum width that limits the size of the content. This content includes ...

Transforming images with Imagick

I've been trying to generate thumbnails from PDF uploads using Imagick. I have a script that is supposed to handle this task, but unfortunately, it only uploads the file without creating a thumbnail. I know some of you may find this basic, but PHP is ...

How to vertically align an image within a div that has a variable height

Is there a way to center an image vertically within a div that is 1/5 of the screen's height? I have managed to horizontally center the image, but vertical alignment seems tricky. Here's the code I've tried so far: http://jsfiddle.net/ws911 ...

A picture placed side by side with a list

Could someone please help me figure out what I'm doing incorrectly? <div class="row"> <ul class='list-group .col-md-6'> <li>1</li><li>1</li><li>1</li> </ul> <div> ...

Attempting to prevent the use of the <p> tag solely before the text

My toggle function is not working correctly in my FaQ section. When a user clicks on a topic, the bottom section should appear, but the <p> tag is being displayed across the entire line instead of just one word.. Here is an image to help illustrate ...

Discovering the reason behind a DOM element's visual alteration upon hovering: Where to start?

Visit this page, then click on the next button to navigate to the time slots section. As you hover over any time slot, you will notice a change in appearance. Despite inspecting Chrome's developer tools, I was unable to locate a style with a hover dec ...

Transforming React drag and drop page builder state into a functional html, css, and js layout

Currently, I am in the process of developing a drag and drop UI builder for react-based app frameworks. Before incorporating drag and drop functionality, my main focus is on rendering a page layout based on a structured array stored in the state. I have a ...

The border should not start at the left of the page; instead, I would like it to begin at the letter "T" in "Tech."

I am having an issue with the bottom border starting from the extreme left of the page. I want it to start from the letter "T" in Tech instead. #page-container { width: 1250px; margin: 0 auto; } h2 { font-weight: normal; padding-left: 15px; ...

What is the best method to remove the x and up/down arrow components of an input date field?

My main objective is to have the orange triangle display in the box, but I'm unsure if CSS or another method is needed to remove the two elements on the left side of the triangle. Is there a way to achieve this? Currently, I am using the input type d ...

Tips for creating two columns within a Bootstrap row, one with a form and the other with an image, that are both the same height and responsive

I am facing an issue with my bootstrap columns. One column has a form, while the other contains an image. The image section is set to 100% width, making it responsive when the screen size changes. However, the form remains at a fixed height regardless of t ...

Is it possible to adjust the viewport to a size larger than 1024?

This site we're examining is not responsive and has a width of about 1230 pixels. When viewed on mobile devices, some content is cut off from the right side due to compression, resulting in approximately a 10% loss. The issue becomes more noticeable ...

HTML input field template

Is there a way to limit the HTML text box to only allow specific patterns such as: A1+A2*A3 It must consist of alphanumeric characters (A1 to A5) 2) It should be able to recognize and accept arithmetic operators in the specified format above. I am util ...