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

What is the URL I need to visit in my browser to monitor updates while running npm?

I am interested in utilizing npm to monitor any changes made in my project and immediately view them in my browser. Essentially, I have been implementing npm using this modified code snippet from this source, which allows me to run the command npm run buil ...

Why is my JavaScript code running but disappearing right away?

I've encountered an issue with the code I wrote below. It's supposed to display the user's names when they enter their name, but for some reason, the names keep appearing and disappearing immediately. What could be causing this problem? Her ...

Finding the location of PIE.htc in the Firebug tool

After encountering issues with CSS3 properties not working on IE 7 and IE 8, I decided to include PIE.HTC. Visit this link for more information Upon viewing the page in IE, I realized that the CSS3 properties were not being applied as expected. I attempt ...

Save a randomly generated string in the Session, which will be replaced when accessed through a different PHP file

I have created a form with a hidden input field, and its value is dynamically set using a function. <?php class Token { public static function generate(){ return $_SESSION['token'] = base64_encode(openssl_random_pseudo ...

Programmatically toggle the visibility of an ion fab button

Looking for assistance in finding a method to toggle the visibility of a particular button within the collection of buttons in an ion-fab ...

How come the inclusion of a DOCTYPE tag impacts the styling of my CSS?

I am puzzled why the code below renders correctly without any issues until I add a doctype declaration: <body style="margin:0; padding:0; background-color:#eeeeee"></body> <div id="HeaderContainer" style="background-color:#eeeeee; color:Bl ...

React Js: Data not being properly updated in the application state

Presenting App.js - import './App.css'; import { connect } from 'react-redux' import { ActionChangeName } from "./Actions/Action"; function App(props) { return ( <div className="App"> <div> ...

Displaying negative values highlighted in red on Datatables platform

After successfully integrating the datatables on my VF page, I now have one final requirement: to display any negative values in red and bold within numerical columns. In my Salesforce implementation, I am using <apex:datatable> for my table. Each nu ...

Instruct Smarty to display the block exactly as it is

Struggling to inline some JavaScript code into the Smarty template files due to the {ldelim} {rdelim} markers. Is there a way to instruct Smarty to disregard the markup and just output it as is? Any similar approach like CDATA blocks in XML? Just demonstr ...

Struggling to generate package using manifoldjs

Excited to dive into the new tool called ManifoldJS introduced by Microsoft at Build 2015, I'm facing some challenges. My website is up and running as a basic HTML- and JS-based app using Angular and TypeScript. I've even created a manifest.json ...

Detect the element that initiated the AJAX call in Jquery event handling

My goal is to capture the beforeSend event for all form submits on my site without interfering with jquery.unobtrusive-ajax.js. I've attempted the following method: $(document).on("ajaxSend", function (e, request, settings) { console.log ...

Integrating Material-UI Dialog with Material-table in ReactJS: A Step-by-Step Guide

I have implemented the use of actions in my rows using Material-Table, but I am seeking a way for the action to open a dialog when clicked (Material-UI Dialogs). Is there a way to accomplish this within Material-Table? It seems like Material-UI just appen ...

Having trouble resolving errors encountered while running the `npm run build` command, not sure of the steps to rectify

I am currently working on my first app and attempting to deploy it for the first time. However, I have encountered an error that I am unsure of how to resolve. When running "npm run build", I receive the following: PS C:\Users\julyj\Desktop& ...

Troubleshooting Query Param Problems in EmberJS Route Navigation

("ember-cli": "2.2.0-beta.6") A search page on my website allows users to look for two different types of records: Users or Organizations. The URL for this search page is /search and I have implemented query parameters to maintain the state and enable ba ...

Adjust the size of the image obtained from the JSON data

I am currently working on parsing JSON data which includes an image field that I want to adjust to a specific size. Despite my many attempts at tweaking the code, I seem to have lost track of why it is not functioning as desired. JSON var items=[]; ...

What could be causing my THREE.js Documentation Box to malfunction?

I am a newcomer trying to get the hang of THREE.js. I delved into the THREE.js Documentation and attempted to implement the code, but when I loaded my HTML page, it appeared blank. I am at a loss for what to do next. I utilized Visual Studio Code for codin ...

In Javascript, a variable is being defined by combining a string with another variable through concatenation

Hey, I'm relatively new to working with Javascript and am facing an issue that I believe can be resolved easily with the right syntax. The problem lies in setting a variable (totalRow1) where it needs to be concatenated with a string and another vari ...

jquery combobox with overlapping autocomplete suggestions

Encountering an issue with the jquery autocomplete combobox where they overlap when positioned side by side. Referencing this link for guidance: http://jqueryui.com/autocomplete/#combobox <!doctype html> <html lang="en"> <head> <me ...

Issue with React application and nginx configuration causing components not to switch when using router functionality

I have encountered an issue while trying to deploy my React app using nginx. The problem I am facing is that when I change routes, for example to /about, the front end does not update and remains on the index page. Here is the configuration in sites-avai ...

Guide on setting a value in $(document).ready using code behind

I am currently working on a .NET application with the use of Twitter Bootstrap. My main challenge right now is retrieving data from a .aspx.cs page to a .aspx page. Here's a look at my code: strObject.cs public class strObject { public string Nam ...