skip to Main Content

I need to obtain max-width in px to use it in a Javascript code but that may be defined in other units in CSS.
Do you have any ideas on how to obtain that using JS?

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

2

Answers


  1. You can use offsetWidth to get the total width of the parent div in pixels, and then derive the max-width of the needed div by multiplying it by the percentage you got earlier:

    const ele = document.querySelector("div")
    const parentEle = ele.parentNode
    let maxWidthPercentage = parseFloat(window.getComputedStyle(ele).maxWidth)/100;
    console.log(maxWidthPercentage)
    let derivedWidth = (parentEle.offsetWidth * maxWidthPercentage)
    console.log(derivedWidth)
    
    // offsetWidth for accuracy check
    console.log(ele.offsetWidth)
    div {max-width: 50%}
    <div>Lorem, ipsum.</div>
    Login or Signup to reply.
  2. Just multiply the percentage value by the width of its parent element.

    const 
        child = document.querySelector("#bar"),
        parent = child.parentNode,
        childMaxWidth = getComputedStyle(child).maxWidth.replace(/[^d.]/g, "") / 100,
        parentWidth = getComputedStyle(parent).width.replace(/[^d.]/g, "");
        
    console.log(`
    Child's max-width: ${childMaxWidth * 100}%
    Parent's width: ${parentWidth}px
    Child's max-width in px: ${childMaxWidth * parentWidth}px`);
    #foo{
      width: max-content;
      height: max-content;
    }
    
    #bar{
      max-width: 95%;
      max-height: max-content;
    }
    <section id="foo">
      <p id="bar">Lorem ipsum</p>
    </section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search