Getting width of an element defined in CSS in em

21,758

Solution 1

use 'offsetWidth' to access the menu's width

var div1 = document.createElement('div'), 
css = document.getElementById('menu').offsetWidth;

console.log(css);
div1.style.width = css + "px";

Solution 2

Use getComputedStyle:

var css = document.getElementById('menu');

console.log(window.getComputedStyle(css).width);​

http://jsfiddle.net/kj6pQ/6/

Solution 3

Try this way:

var width = window.getComputedStyle(document.getElementById("menu"), null).getPropertyValue("width");
Share:
21,758
Admin
Author by

Admin

Updated on September 21, 2020

Comments

  • Admin
    Admin over 3 years

    I am having trouble getting the width of an element defined in CSS. I figured out how to get the CSS rules using Javascript, but I can't access the width. Menu is fixed width that I defined in CSS using em.

    I am trying to change the width of the div1 based on the browser window minus the fixed menu width.

    Note: I already tried using style.width, but it returns a blank line in the console.

    jsfiddle: http://jsfiddle.net/kj6pQ/

    var div1 = document.createElement('div'), 
    css = getMatchedCSSRules(document.getElementById('menu'));
    
    console.log(css); //works but dont' konw how to access width
    
    div1.style.width = window.innerWidth - <!-- menu width -->;