Centering 2 Divs inside another vertically

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

问题:

I have 2 divs that I want to centre vertically inside another div. At the moment I have:

http://jsfiddle.net/5vpA3/1/

Now I understand what is going on here, but I want the left div to be vertically aligned within that container and the right div the same. But they are vertically aligning as a pair and not individually. I have tried various things but can't seem to get it work.

回答1:

Live Demo

  • Remove float: left from #left and #right.
  • Instead, use display: inline-block:

    #left, #right {     display: inline-block;     vertical-align: middle; } 
  • Due to using display: inline-block, you have to deal with the whitespace issue. I chose to remove the whitespace in the HTML between </div> and <div id="right">. See here for what happens if you don't do that. Removing the whitespace really is the easiest fix, but there are other ways.


回答2:

Like this?

Demo: http://jsfiddle.net/5vpA3/25/

#container {     background-color: #FFFF00; } #left {     height: 150px;     color: #FFFFFF;     background-color: #0000FF;     width: 100px;     margin-left: auto;     margin-right: auto;     position: relative;     left: 0px;     top: 0px; } #right {     height: 80px;     color: #FFFFFF;     background-color: #FF0000;     width: 100px;     margin-left: auto;     margin-right: auto;     position: relative;     left: 0px;     top: 0px; } 


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