chucky
chucky

Reputation: 151

Safari not rendering margin-top % values like other browsers

I have asked this question before, but thought I'll be clearer. It seems that margin-top in % value does not display the same on Safari, as it does on Chrome, Firefox and IE. In px it displays correctly and margin-left % also.

Here is an example to make comparisons: Fiddle

* {
   margin:0;
   padding:0;
 }

.A {
   background-color: blue;
   height: 200px;
   position:relative;
 }

.B {
   left: 50px;
   margin-top:15%;
   width:20px;
   height:20px;
   background-color: red;
   position:absolute;
}

I really need to use a % value on margin-top as it is for a responsive design feature. Using top does not scale the object according to the window size.

Are there known issues, and if so (probably asking a big thing) a way to only target Safari as a browser so I can have custom values for the style sheet?

Upvotes: 3

Views: 6004

Answers (1)

Luke
Luke

Reputation: 5612

Yes, according to the W3C standards, margins defined using percentages should be calculated with respect to the width of the containing block.

Ref: (http://www.w3.org/TR/2011/REC-CSS2-20110607/box.html#margin-properties)

However, it appears that Safari calculates top/bottom margin percentages with respect to the height of the containing block, which makes more logical sense, but is nevertheless incorrect as far as W3 standards go.

I don't believe there is a CSS solution for this. You could try some jQuery to target only Safari, get the width of div.A and use it to calculate the margin-top for div.B.

Something like:

    var width = $('.A').width();
    var topMargin = width * 0.15;
    if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {                  
        $('.B').css('margin-top', topMargin+'px')
    }
    else {
    };;

Here's an example page: http://www.indieweb.co.nz/testing/safari-margin-percentage.html

Note: This JS only alters the margin when the page is loaded - it won't change dynamically if you manually drag the edges of your browser window; you will need to refresh the page. Wasn't sure if you required that functionality. Let me know if you do and I'll have a look.

Upvotes: 4

Related Questions