CSS calc not working in Safari and fallback

2019-01-09 01:24发布

问题:

I have this layout I am working on. It strongly depends on CSS calc to do the necessary calculations.

width: -webkit-calc(50% - 20px);
width: -moz-calc(50% - 20px);
width: calc(50% - 20px);

Now, I can't get this to work in Safari. Is there something I'm doing wrong?

And also, is there a way I can introduce a fall-back mechanism for browsers that don't support it? Percentage wont do a good job, since I have to subtract the object in the middle, from the two on the side.



Thanks.

回答1:

The way I solved this problem, is introducing a pure CSS fall-back, that older browsers that don't support CSS calc would only read.

figure.left {
    width: 48%;
    width: -webkit-calc(50% - 20px);
    width: -moz-calc(50% - 20px);
    width: calc(50% - 20px);
}

The left and right panels, get a width of 48% if the browser cannot read the calc values.

figure.logo {   
    min-width: 40px;
    width: 4%;
    width: -webkit-calc(40px);
    width: -moz-calc(40px);
    width: calc(40px);
}

And the logo, which sits in-between the two panels, gets a width of 4%. And also a minimum width of 40px. And if the calc values can be read by the browser, they are 40px.



回答2:

You're code looks fine, so I think the problem is browser compatibility. According to Mozilla Documentation, this feature works in Chrome, Firefox, and IE (the newer versions), but is nonexistent in Opera and is buggy in Safari. this question for more compatibility information. A much safer fallback/alternative would be to do your calculations in Javascript:

if ($(document).width() >= 750){
  $("#yourElementsID").css("width",$("#yourElementsID").width()*0.5-20)
} else if ($(document).width() >= 400){
  // do something here for smaller values
}

You can use the jQuery .width() function to detect the width of the document, then set the width of your elements accordingly. But just warning you, try to keep as many of your styles outside of your scripts and inside your stylesheets because otherwise it will be unmaintainable.

If it still doesn't work in some browsers, use Modernizr to detect the browser/version/OS and then redirect them to a different version of the page.

Edit 1: Added responsiveness
Edit 2: Removed Interval
Edit 3: Added mention of Modernizr