CSS calculator validation not working in Chrome

I was looking for a way to determine if the browser supports CSS calc and found this: How to check if CSS calc () is accessible using JavaScript? I modified solution number 5 as follows:

help = $('<img src="/images/buttonup.png">')
help.css({ width: "10px" });
help.css({ width: "calc(10px + 10px)" });
if (help.width() == 20) var calcSupport = true; else var calcSupport = false;

Unfortunately, this does not work in Chrome: help.width () returns 0, although the Chrome browser calculates exactly. It works great in Firefox. What am I doing wrong?

+4
source share
3 answers

Chrome cannot reliably provide computed styles for an element that has not been added to the DOM.

So, you can add an element to body, read its width and delete it.

var el = document.createElement('img');
el.style.width = "calc(10px + 10px)";
document.body.appendChild(el);
var calcSupport = getComputedStyle(el).width == '20px';
document.body.removeChild(el);

, getComputedStyle, jQuery $(el).width() == 20.

+3

, , .

HTML:

<img src="http://davidwalsh.name/demo/css3logo250.jpg" class='img'>

CSS

.img{
   width: 100px;
   width: -webkit-calc(10px + 10px); 
   width:    -moz-calc(10px + 10px); 
   width:      -o-calc(10px + 10px);
}

JavaScript:

var help = $(".img");
if(help.width() == 20){
   var calcSupport = true;
   alert('calc() is supported');
}else{
   var calcSupport = false;
}

JSFiddle

+1

Better to use CSS.supports:

var calcSupport = CSS.supports("width", "calc(10px + 10px)");
0
source

All Articles