Html – Vertically and horizontally center HTML in UIWebView

csshtmliosuiwebview

I'm trying to vertically and horizontally center content of an unknown height in a UIWebView.

What I have right now works great in Safari:

http://jsfiddle.net/HT9J5/

However, it does not look right when presented in a UIWebView:

enter image description here

Any ideas how to get this to work? One thing I cannot do is set the viewport meta, because this needs to work when presenting the UIWebView in a modal view controller on iPad, where it is not the full width of the screen:

<meta name="viewport" content="width=device-width;initial-scale=1.0;maximum-scale=1.0;"/>

Best Answer

I tried your example and it works fine in an UIWebView. I don't know how you load your HTML / CSS. Are you sure that the CSS is loaded correctly? Have you set the frame of your UIWebView?

Here is the code that works for me. I set the frame of the UIWeb smaller than the screen size because you mentioned presenting it modally.

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *htmlString = @"<html><head><style type='text/css'>html,body {margin: 0;padding: 0;width: 100%;height: 100%;}html {display: table;}body {display: table-cell;vertical-align: middle;padding: 20px;text-align: center;-webkit-text-size-adjust: none;}</style></head><body><p><strong>Title</strong></p><p>A long explanation about what's going on and all that.</p><p><a href='#'>A link</a></p></body></html>​";

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10.0, 10.0, 300.0, 400.0)];
    [self.view addSubview:webView];
    [webView loadHTMLString:htmlString baseURL:nil];

    [webView release];
}

enter image description here