JQuery Mobile - align button in middle of screen
This question is regarding JQuery Mobile. I have a screen which simply contains a heading and a button. By default, this appears on top of the screen. I was wondering how to align it at the middle of the screen.
Che开发者_运维百科ers.
I assume that you want to vertically align the button only, and leave the header at the top of the page. The easiest way to center something vertically is to position it absolutely and set it's top to 50%. That will put the top of the content in the middle of the screen.
If you want the vertical center of the content in the middle of the screen, then you have to know the height of the content being centered and move the content up by half of that amount using a negative top margin. With the padding and borders added by jQuery Mobile, a button with 1em font-sized text will have about 2.4em height and need to move up by 1.2em.
Here is an example, I've put my button in a div and absolutely aligned the div:
<!DOCTYPE html>
<html><head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" />
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.js"></script>
</head><body>
<div data-role="page">
<div data-role="header">Header</div>
<div data-role="content">
<div style="position: absolute; top: 50%; margin-top: -1.2em;">
<a href="index.html" data-role="button">Button</a>
</div>
</div>
</div>
</body></html>
When trying this myself, the width of the button went from the full width of the screen to it's smallest possible width. If you still want the button to stretch across the screen then add "width:100%; margin-left: -1em;" to the containing div's style attribute.
精彩评论