Html 如何在动态高度 div 中垂直居中文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10939288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:54:23  来源:igfitidea点击:

How can I vertically center text in a dynamically height div?

htmlcsscentering

提问by Albion

<body>
    <div style="position:absolute; height:100%; width:100%;">
        <h1 style="text-align:center;">Text</h1>
    </div>
</body>

How can I vertically center the h1 tag inside of the div tag, no matter how tall the div element is? i.e. If the user changes his browser height, I want the h1 to vertically align in the center, according to the new height.

无论 div 元素有多高,如何将 h1 标签垂直居中放置在 div 标签内?即如果用户更改了他的浏览器高度,我希望 h1 根据新高度垂直居中对齐。

Thanks.

谢谢。

回答by Zuul

The best solution I've ever encountered is to make use of the displayproperty and set the wrapper element as a tableto allow the usage of vertical-align:middleon the element to be centered:

我遇到的最好的解决方案是利用该display属性并将包装元素设置为 atable以允许vertical-align:middle在元素上使用 居中:

See thisworking Fiddle Example!

看到这个工作小提琴示例

HTML

HTML

<body>
    <div>
        <h1>Text</h1>
    </div>
</body>

CSS

CSS

body {width: 100%; height: 100%;}   /* this is just to "view" the div height...*/

div {
    position:absolute; height:100%; width:100%;
    display: table;
}
h1 {
    display: table-cell;
    vertical-align: middle;
    text-align:center;
}


TESTED ON

已测试

Windows XP Profissional vers?o 2002 Service Pack 3

Windows XP 专业版 2002 Service Pack 3

  • Internet Explorer 8.0.6001.18702
  • Opera 11.62
  • Firefox 3.6.16
  • Safari 5.1.2
  • Google Chrome 18.0.1025.168 m
  • Internet Explorer 8.0.6001.18702
  • 歌剧 11.62
  • 火狐 3.6.16
  • Safari 5.1.2
  • 谷歌浏览器 18.0.1025.168 m

Windows 7 Home Edition Service Pack 1

Windows 7 家庭版服务包 1

  • Internet Explorer 9.0.8112.164211C
  • Opera 11.62
  • Firefox 12.0
  • Safari 5.1.4
  • Google Chrome 18.0.1025.168 m
  • Internet Explorer 9.0.8112.164211C
  • 歌剧 11.62
  • 火狐 12.0
  • Safari 5.1.4
  • 谷歌浏览器 18.0.1025.168 m

Linux Ubuntu 12.04

Linux Ubuntu 12.04

  • Firefox 12.0
  • Chromium 18.0.1025.151 (Developer Build 130497 Linux)
  • 火狐 12.0
  • Chromium 18.0.1025.151(开发人员版本 130497 Linux)

回答by Wex

The answer I find the least obtrusive and least confusing requires inserting a <span>tag before the <h1>element: http://jsfiddle.net/Wexcode/axRxE/

我发现最不突兀和最容易混淆的答案需要<span><h1>元素之前插入一个标签:http: //jsfiddle.net/Wexcode/axRxE/

HTML:

HTML:

<div>
    <span></span><h1>Text</h1>
</div>?

CSS:

CSS:

div { text-align: center; /* horizontally center */ }
div span {
    height: 100%;
    vertical-align: middle;
    display: inline-block; }
div h1 {
    vertical-align: middle;
    display: inline-block; }?

Expanding this technique to vertically-align to the browser-height: http://jsfiddle.net/Wexcode/axRxE/1/

将此技术扩展为与浏览器高度垂直对齐:http: //jsfiddle.net/Wexcode/axRxE/1/

回答by Tom McDonough

I have the easiest 3 lines of css which are going to blow your mind and you will be thinking "Why didn't I think of this initially". Use this on the element you would like to be positioned vertically centered and the parent container just add a height of 100%.

我有最简单的 3 行 css,它们会让你大吃一惊,你会想“为什么我最初没有想到这一点”。在要垂直居中放置的元素上使用它,父容器只需添加 100% 的高度。

position: relative;
top: 50%;
transform: translateY(-50%);

The position can be either relative, absolute or fixed.

位置可以是相对的、绝对的或固定的。

回答by Zoltan Toth

http://jsfiddle.net/xQBbQ/

http://jsfiddle.net/xQBbQ/

<body>
    <div style="position:absolute; height:100%; width:100%;">
        <h1 style="text-align:center; height:20px; position:relative; top:50%; margin-top:-10px;">Text</h1>
    </div>
</body>

回答by doptrois

There's a cross (desktop) browser solutionto do this with CSS2 + CSS3 and without any Javascript.

有一个跨(桌面)浏览器解决方案可以使用 CSS2 + CSS3 做到这一点,而无需任何 Javascript。

Works in

工作于

  • IE5+
  • Gecko's (Mozilla, Firefox, Netscape 7)
  • Opera 7+
  • Konqueror 3+
  • Webkit Browsers (Safari, Google Chrome)
  • and a lot more (Mobile browsers not tested)
  • IE5+
  • Gecko's(Mozilla、Firefox、Netscape 7)
  • 歌剧 7+
  • 征服者 3+
  • Webkit 浏览器(Safari、Google Chrome)
  • 以及更多(未测试移动浏览器)

Documentation: Vertical Centering in CSSDefinitive Solution with Unknown Height:
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

Clean jsFiddle Example: http://jsfiddle.net/WYgsP/

文档:未知高度的CSS最终解决方案中的垂直居中
http: //www.jakpsatweb.cz/css/css-vertical-center-solution.html

Clean jsFiddle 示例http: //jsfiddle.net/WYgsP/



HTMLHTML

<div class="outerBox">
    <div class="helper">
        <div class="boxWithUnknownHeight">
            any text<br>
            any height<br>
            any content, for example generated from DB<br>
            everything is vertically centered
        </div>
    </div>
</div>?

CSS

CSS

.outerBox {
    display: table;
    height: 400px;
    #position: relative; /* ie hack */
    overflow: hidden;
    border: 1px solid red;
}

.helper {
    #position: absolute; /* ie hack */
    #top: 50%; /* ie hack */
    display: table-cell;
    vertical-align: middle;
}

.boxWithUnknownHeight {
    #position: relative; /* ie hack */
    #top: -50%;
    border: 1px solid green
}?


It works, even if i add text and line-breaks through Firebug etc.
To keep your CSS clean from invalid CSS-Hacks, I'll recommend you to use conditional commentsfor it and create a separate CSS with the browser specific Code.

它可以工作,即使我通过 Firebug 等添加文本和换行符。
为了使您的 CSS 免受无效 CSS-Hacks 的影响,我建议您对其使用条件注释,并使用浏览器特定代码创建一个单独的 CSS。

How vertical centering with unknown height exactly works and why: Detailed description

高度未知的垂直居中如何准确工作以及为什么:详细说明



Other solutionswith display: tableand or display: table-celland or absolute positioning here.

此处使用display: table和或display: table-cell和或绝对定位的其他解决方案

回答by Devin Burke

In 2012, the accepted answer was the correct/best option.

2012 年,接受的答案是正确/最佳选择。

Flash forward 8 years, and flex boxes are supported by every mainstream browser(IE10+):

Flash向前8年,所有主流浏览器(IE10+)都支持flex box

display: flex;
align-items: center;
flex-direction: column;  /* To also center horizontally, change to `rows` or remove */

Note: If you care about IE10, you need to include -ms-prefix versions, per my hyperlink above.

注意:如果您关心 IE10,则需要-ms-根据我上面的超链接包含前缀版本。

回答by heroix

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
body {
    background-color: #0c0c0c;
}
.object {
    background-color: #666666;
    height: 350px;
    width: 600px;
}
.verticalCenter {
    width:600px;
    height:350px;
    position:absolute;
    left:50%;
    top:50%;
    margin:-175px 0 0 -300px;
}
-->
</style>
</head>
<body>
    <div class="verticalCenter">
        <div class="object">cetnered</div>
    </div>
</body>
</html>

You must set height and width in .verticalCenter class the same as of your object (div, flash, image, text) that is to be centered. And margins must be half of these height and width.

您必须在 .verticalCenter 类中设置与要居中的对象(div、flash、图像、文本)相同的高度和宽度。并且边距必须是这些高度和宽度的一半。

I don't think there is solution if you change that object dynamically. Unless, maybe with javascripts.

如果您动态更改该对象,我认为没有解决方案。除非,也许使用 javascripts。

回答by Surreal Dreams

Here's a fairly simple solution. It's mostly based on setting display:table-celland choosing a vertical alignment like middle.

这是一个相当简单的解决方案。它主要基于设置display:table-cell和选择像中间这样的垂直对齐方式。

HTML:

HTML:

<div id="vertical">
    <p>this text is vertically centered.  It's long enough to wrap, and should work for any size chunk of content.</p>
    <p>Heck, it even works with multiple items in the middle.</p>
</div>??

CSS:

CSS:

#vertical {
    display:table-cell;
    vertical-align:middle;
    height: 500px;
    width: 300px;
}?

JSFiddle: http://jsfiddle.net/6Re3E/1/

JSFiddle:http: //jsfiddle.net/6Re3E/1/

回答by Superjova

I use tables for everything. I personally do not enjoy usingdisplay: tableor anything like that when there is something that already exists.

我什么都用桌子。display: table当已经存在某些东西时,我个人不喜欢使用或类似的东西。

<table style="width: 100%; height: 100%;">
    <tr>
        <td>
            <!-- Whatever you want vertically and horizontally centered -->
        </td>
    </tr>
</table>

Using this same method, you can do something like this for your case:

使用相同的方法,您可以为您的案例执行以下操作:

<div id="container-div" style="position: relative">
    <div id="random-content-that-changes-container-height-and-width" style="height: 600px; width: 400px;">
    <div style="position: absolute; top: 0; right: 0; left: 0; bottom: 0">
        <table style="width: 100%; height: 100%;">
            <tr>
                <td>
                    <!-- Whatever you want vertically and horizontally centered -->
                </td>
            </tr>
         </table>
     </div>
</div>

回答by Tooraj Jam

From my point of view, divis not appropriate choice in this case. My suggestion is go for tableand vertical-alignstyle on it's tds.

在我看来,div在这种情况下是不合适的选择。我的建议是随时随地tablevertical-align风格上的td秒。