HTML 和 CSS - 垂直对齐 div

发布于 2024-08-24 07:26:17 字数 339 浏览 2 评论 0原文

我的左侧有一个 div,右侧有文本。文本可以是 2 行或 3 行长,我希望左侧 div 垂直居中于该文本。我在网上查了一下,似乎所有不使用表格来做到这一点的方法都很复杂。有没有简单的方法可以做到这一点?

大多数建议似乎都指向 http://www.jakpsatweb.cz/ css/css-vertical-center-solution.html 使用“CSS 表”。 CSS 表格是正确的选择吗?这真的比仅使用 HTML 表格更好吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

薄情伤 2024-08-31 07:26:17

是的,CSS 表格比 HTML 表格更好,因为它们不暗示任何语义,而是明确用于描述表示。

但是,对于您的情况,CSS 的 vertical-align 可以工作。例如:http://jsbin.com/itoyo3/edit

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.

困倦 2024-08-31 07:26:17

你可以用绝对定位来做到这一点;

将代码更改为如下所示:

无论此处内容

内容

像这样设置你的CSS:

#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*/
}

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*/
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文