HTML and CSS - Vertical align divs

末鹿安然 提交于 2019-12-24 10:56:45

问题


I have a div on the left hand side, and text on the right hand side. The text can be either 2 or 3 lines long, and I want the left hand div to be vertically centered to that text. I've looked online and it seems that all the ways to do this without using tables are complicated. Is there an easy way to do this?

Most suggestions seem to point to http://www.jakpsatweb.cz/css/css-vertical-center-solution.html which uses "CSS tables". Are CSS tables the way to go? Is that really better than just using HTML tables?


回答1:


Yes, CSS tables are better than HTML tables because they do not imply any semantic meaning but are explicitly used to describe presentation.

However, for your case CSS's vertical-align works. For example: http://jsbin.com/itoyo3/edit.




回答2:


You could do it with absolute positioning;

Change your code to look like this:

<div id="right-content"><div id="the-left-hand-div">whatever goes here</div><p>The content</p></div>

Set your css up like this:

#right-content {
    float: left;
    position: relative;
    margin-left: /*the width of the the left div content plus any margin you want*/
}

#the-left-hand-div {
    position: absolute;
    left: /*negative width of the the-left-hand-div plus any margin you want*/
    top: /*height of #right-content - the-left-hand-div divided by 2 - this could be a negative value if the-left-hand-div is higher than the right-content*/
}


来源:https://stackoverflow.com/questions/2394976/html-and-css-vertical-align-divs

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