Get the maximum width in pixels through JavaScript when it is specified in different units within the CSS

I'm looking to retrieve the max-width value in px from CSS for use in a JavaScript code. The challenge is that this value might be specified in different units in the CSS file. Any suggestions on how to achieve this using JavaScript?

const element = document.querySelector("div")
const elementMaxWidth = window.getComputedStyle(element).maxWidth
console.log(elementMaxWidth)
div {max-width: 50%}
<div>Lorem, ipsum.</div>

Answer №1

Just a heads up: There aren't any built-in solutions for this, so the method outlined here is kind of a hack. This has only been tested on Chrome and Firefox, so it might not work on other browsers.

const element = document.querySelector("div");
const previousWidth = element.style.width;
element.style.width = "100000000cm"; /* equals 1000km */
const maxWidthOfElement = element.offsetWidth;
element.style.width = previousWidth;
console.log(maxWidthOfElement + "px");
div {
  max-width: 50%
}
<div>Lorem ipsum.</div>

Answer №2

To find the total width of a percentage value, simply multiply the percentage by the parent element's width.

const 
    innerBox = document.querySelector("#box"),
    outerBox = innerBox.parentNode,
    childMaxWidth = getComputedStyle(innerBox).maxWidth.replace(/[^\d\.]/g, "") / 100,
    outerBoxWidth = getComputedStyle(outerBox).width.replace(/[^\d\.]/g, "");
    
console.log(`
Inner box max-width: ${childMaxWidth * 100}%
Outer box width: ${outerBoxWidth}px
Total width in pixels: ${childMaxWidth * outerBoxWidth}px`);
#container{
  width: auto;
  height: auto;
}

#box{
  max-width: 85%;
  max-height: auto;
}
<div id="container">
  <p id="box">Lorem ipsum</p>
</div>

Answer №3

To obtain the width of the parent div in pixels, use the offsetWidth property and then calculate the max-width of the required div by multiplying it with a previously obtained percentage:

const element = document.querySelector("div")
const parentElement = element.parentNode
let maxWidthPercentage = parseFloat(window.getComputedStyle(element).maxWidth)/100;
console.log(maxWidthPercentage)
let calculatedWidth = (parentElement.offsetWidth * maxWidthPercentage)
console.log(calculatedWidth)

// Checking accuracy with offsetWidth
console.log(element.offsetWidth)
div {max-width: 50%}
<div>Lorem ipsum.</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

Using jQuery to add HTML elements before the content of a list

I'm facing a challenge in dynamically adding new elements to my list. Through ajax, I retrieve HTML data from my database and aim to iterate through each new <li> element to gradually prepend them to the top of the list. This is the snippet of ...

Adding elements to a JavaScript modal using a loop

When working with JavaScript, I am dynamically adding content to a modal. This involves populating different data into various table rows and cells within the modal. <table class="table table-striped"> <thead> <tr> ...

The text-center alignment in Bootstrap doesn't seem to be applying to buttons

After spending a considerable amount of time trying to center two buttons in Bootstrap, I came across the "text-center" class offered by Bootstrap. However, no matter where I include this class, it doesn't seem to have any effect on the alignment of t ...

Conflict in the naming and scoping of IE7 and IE8

While reviewing some code, I encountered a problem in Internet Explorer 7 and 8. Despite the constructor executing properly when stepped through, upon returning I received an error stating "Object does not support this property or method." How frustrating! ...

What is the best way to retrieve the background color of specific table cells?

I have a table that showcases various pieces of information. One interesting feature I added is a notes column, which includes a tooltip created using CSS and jQuery. However, there seems to be an issue with the tooltip's behavior - when I hover over ...

A dynamic image carousel featuring multiple images can be enhanced with fluid movement upon a flick of

I am trying to enhance this image slider in HTML and CSS to achieve the following objectives: 1. Eliminate the scroll bar 2. Implement swipe functionality with mouse flick (should work on mobile devices as well) 3. Make the images clickable .slider{ ove ...

Receive a notification for failed login attempts using Spring Boot and JavaScript

Seeking assistance with determining the success of a login using a SpringBoot Controller. Encountering an issue where unsuccessful logins result in a page displaying HTML -> false, indicating that JavaScript may not be running properly (e.g., failure: f ...

The Bootstrap modals seem to be invisible within the Rails application

Currently, I am integrating jquery into the devise views of a sample rails application. My intention is to test it on a sample app before implementing it in a production code. The controller and view for welcome are already set up. The routes.rb file loo ...

The jQuery datetimepicker fails to reflect changes made to the minDate property

I have encountered a datetimepicker object that was previously set up with the following configuration: $('#startDate').datetimepicker({ monthNames: DATE_TIME_MONTHS_NAMES, monthNamesShort: DATE_TIME_MONTHS_NAMES_SHORT, dayNames: DAT ...

ways to validate the calling function in jquery

One of the challenges I'm facing is identifying which function is calling a specific error function that is used in multiple places within my code. Is there a method or technique to help determine this? ...

Requesting data from the application to the MongoDB database is currently malfunction

Currently, I'm utilizing Express and passport to develop an application. Everything has been going smoothly so far, but I've encountered a problem when attempting to retrieve data from my mongo database. Strangely enough, I am able to successfull ...

Issue with mediaelement in Angular 8: video playback does not display after 2 seconds

I'm encountering an issue with MediaElement js when trying to play videos in .m3u8 format within a slider containing multiple videos. Whenever I click on the play button for any video, only a 2-second clip is shown before the video disappears. Any as ...

Detecting a click event within a hidden div located behind another visible div

I am facing an issue with triggering ng-click in a div that is covered by another div. The current scenario I have is as follows: Basically, I need to activate ng-click on the yellow circle when it is clicked. However, there is another div positioned abov ...

A tutorial on how to customize the hover effect for TableHead Column Identifiers in MaterialUI by adjusting

I'm struggling to customize the appearance of child th elements using the TableHead component from MaterialUI. While I've been successful in modifying various properties, I'm facing difficulty in changing the hover color. Below is the snipp ...

Tips for positioning the text and icon within a tag nestled in a paragraph tag?

Need help aligning text and icons inside paragraph tags on a tag. Here is the HTML code I'm currently using: <div class="application-intro"> <p><a class="btn" href=""><i clas ...

Iterating over an object and inserting values into a JavaScript object using the ascending count as the identifier

Illustration: { Are you a coffee drinker?: yes, Do you like to exercise regularly?: no, How often do you eat out at restaurants?: 3 times a week, What is your favorite type of cuisine?: Italian } Results: {yes: 1, no: 1, 3 time ...

Troubleshooting: Why isn't my CSS fixed position working for my sticky

I have a simple jQuery code snippet that is supposed to make the navigation element sticky by applying a class with position: fixed. However, I'm facing an issue on my Commerce platform where the fixed position property doesn't seem to work corre ...

Create a new array of objects by extracting specific properties from an existing array of objects

Consider the input array below: const initialArray = [{name: 'john', age: 12, height: 178, likes: 'music'}, {name: 'mike', age: 22, height: 181, likes: 'sport'}, {name: &ap ...

Vue Loader: Multiple loaders for a single file extension

Currently, I'm experimenting with incorporating SVG into my vue-loader/webpack template project. I'm in need of loading different types of SVGs: Icons: these are utilized within my components and loaded using svg-inline loader for customizatio ...

using `clear: both` does not stop text from wrapping

Currently, I am facing an issue with positioning 3 divs in my layout. Two of the divs are floating to the left and right respectively, while the third one should be placed under the two others. I tried using clear: both but it doesn't seem to work as ...