mayonaise
mayonaise

Reputation: 129

Right padding/margin not working correctly in UIWebView (embedded mobile safari)

This is being used in a UIWebView inside an iOS app. It appears to work fine in regular Mobile Safari, but not in the embedded browser.

Basically, I have some HTML and CSS. The HTML element has some padding applied all around, and the BODY element does not. What I expect to see, is the contents of the BODY surrounded by empty space. In desktop Safari, this works. But for some reason, in Mobile Safari (embedded Safari), the Right padding of the HTML tag is ignored, or maybe the BODY tag is being stretched - not sure which. Please see these screenshots for clarification:

enter image description hereMobile Safari

Notice how the padding seems to disappear in the Mobile Safari example. Note: these are just images I mocked up in photoshop, not screenshots, but the behavior is the same.

Here is the code (simplified, of course):

<html>
<head>
<style>
html {
    background-color: #FFF;
    padding: 10px;
}
body {
    background-color: #0F0;
}
</style>
<body>
<div> ... some stuff ... </div>
</body>
</html>

To be sure something wasn't stretching the width of the BODY tag, I tried removing all the unneeded HTML and CSS, and basically just having an empty BODY tag with a green background, like the images show. This still has the same issue. I have also tried putting margins around the BODY tag instead of padding in the HTML tag, and this doesn't work.

Edit: I have also tried setting the box model to border-box, as discussed here, but it doesn't work.

Any ideas?

Upvotes: 1

Views: 4914

Answers (2)

Frade
Frade

Reputation: 2988

from this answer (it worked for me)

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *padding = @"document.body.style.margin='0';document.body.style.padding = '0'";
    [webView stringByEvaluatingJavaScriptFromString:padding];
}

Upvotes: 3

mayonaise
mayonaise

Reputation: 129

It turned out the UIWebView wasn't being initialized with any dimensions. It wasn't being explicitly initialized at all, for example [[UIWebView alloc] initWithFrame:....]. Explicitly initializing it with the proper dimensions fixed the issue.

Upvotes: 1

Related Questions