开发者

CSS: Vertical and horizontally centered

Challenge: you have an empty body tag. Its only child is a div. The div's height and width are unknown. Make the contents of the div vertically and horizontally centered, using CSS/HTML alone (no JavaScript).

For a test sandbox, fork: http://jsf开发者_如何学Goiddle.net/pB9hK/


I don't think there's an "ideal" cross-browser pure CSS solution for vertical-centering that's not more trouble than it's worth. If you want to use a single line of jQuery...

$('#adiv').css('marginTop', ($(window).height() - $('#adiv').height()) / 2);

CSS...

#adiv {
    width: 60%;
    margin: 0px auto;
}


For Horizontal use

body>div#center
{
text-align: center;
}

for Vertical use

body>div#center
   {
   display: table-cell;
   vertical-align: middle;
   }


Use display:table. You'll find an example at this link (Bredele vertical centering). Here a snippet I use:

html {
  display: table;
  table-layout: fixed;
  width: 100%; 
  height: 100%;
}

body {  
  display: table-cell;  
  width: 100%; 
  height: 100%;
  vertical-align: middle;
  margin:0;
}

#center {
  margin: auto;
}

As you asked, the height and width of div#center are unknown.

Olivier


Here is a reply to wdm. A plain JavaScript version for vertical centering.

var el = document.getElementById('main');
el.style.marginTop = (document.body.offsetHeight - el.offsetHeight) / 2;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜