How to center a div vertically?

匿名 (未验证) 提交于 2019-12-03 01:47:02

问题:

I have a div that I want to center horizontally and vertically.

For the horizontal issue everything is great, but I have a problem with the vertical alignment.

I tried this:

#parent {     display: table; }  #child {     display: table-row;     vertical-align: middle; } 

but this doesn't work.

回答1:

If you only have to support browsers that support transform (or its vendor prefixed versions), use this one weird old trick to vertically align elements.

#child {     position: relative;     top: 50%;     transform: translateY(-50%); } 

If you have to support older browsers, you can use a combination of these, but they can be a pain due to the differences in rendering block vs table.

#parent {     display: table; }  #child {      display: table-cell;      vertical-align: middle; } 

If your height is fixed and you need to support those really old, pesky browsers...

#parent {    position: relative; }  #child {    height: 100px;    position: absolute;    top: 50%;    margin-top: -50px; } 

If your height is not fixed, there is a workaround.

See it on jsFiddle.



回答2:

Having the parent property as, display:table and child property as display: table-cell and vertical-align: middle worked for me.



回答3:

First off, treating non-table markup as tables (with display:table and friends) isn't cross-browser. I don't know which browsers you need to support but certainly IE6 won't do this. But, if your targeted browser do all support display:table I can give you some tips.

The vertical centering approach you're looking for (using table layout) depends on having a TD with vertical-align:middle, then inside of that a single block element will vertically center. So I think what you want is:

#parent { display:table-cell; vertical-align:middle; } #child { /* nothing necessary, assuming it's a DIV it's already display:block */ } 

It's ok to use table-cell with no surrounding table-row and table, the browser infers the needed table wrapping elements for you.



回答4:

here is another way when you don't know the inner div size or whatever, you may use % here and there to fix the "centering" ....

the idea is that your top value is half the height of your child element as to create the centering illusion

Here's the code:

hello

and for the styling:

#parent {    position: relative;     height: 300px;     width:200px;     background-color:green; }  #child {    height: 50%;    width: 50%;     position:relative;     top:25%;     left:25%;    background-color:red; } 

Here you can see it in action http://jsfiddle.net/Wabxv/



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!