Html 如何垂直对齐div中的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2939914/
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 03:16:13  来源:igfitidea点击:

How do I vertically align text in a div?

htmlcssvertical-alignment

提问by shinjuo

I am trying to find the most effective way to align text with a div. I have tried a few things and none seem to work.

我试图找到将文本与 div 对齐的最有效方法。我已经尝试了一些东西,但似乎没有任何效果。

.testimonialText {
  position: absolute;
  left: 15px;
  top: 15px;
  width: 150px;
  height: 309px;
  vertical-align: middle;
  text-align: center;
  font-family: Georgia, "Times New Roman", Times, serif;
  font-style: italic;
  padding: 1em 0 1em 0;
}
<div class="testimonialText">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

采纳答案by Robert Harvey

Vertical Centering in CSS
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

CSS 中的垂直居中
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

Article summary:

文章摘要:

For a CSS 2 browser, one can use display:table/display:table-cellto center content.

对于 CSS 2 浏览器,可以使用display:table/display:table-cell来居中内容。

A sample is also available at JSFiddle:

JSFiddle还提供了一个示例:

div { border:1px solid green;}
<div style="display: table; height: 400px; overflow: hidden;">
  <div style="display: table-cell; vertical-align: middle;">
    <div>
      everything is vertically centered in modern IE8+ and others.
    </div>
  </div>
</div>

It is possible to merge hacks for old browsers (Internet Explorer 6/7) into styles with using #to hide styles from newer browsers:

可以将旧浏览器 (Internet Explorer 6/7) 的 hack 合并到样式中,并使用#从新浏览器中隐藏样式:

div { border:1px solid green;}
<div style="display: table; height: 400px; #position: relative; overflow: hidden;">
  <div style=
    "#position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
    <div style=" #position: relative; #top: -50%">
      everything is vertically centered
    </div>
  </div>
</div>

回答by David

You need to add the line-heightattribute and that attribute must match the height of the div. In your case:

您需要添加line-height属性,并且该属性必须与div. 在你的情况下:

.center {
  height: 309px;
  line-height: 309px; /* same as height! */
}
<div class="center">
  A single line.
</div>

In fact, you could probably remove the heightattribute altogether.

事实上,您可以height完全删除该属性。

This only works for one line of textthough, so be careful.

不过,这只适用于一行文本,所以要小心。

回答by Adam Tomat

Here's a great resource

这里有很棒的资源

From http://howtocenterincss.com/:

http://howtocenterincss.com/

Centering in CSS is a pain in the ass. There seems to be a gazillion ways to do it, depending on a variety of factors. This consolidates them and gives you the code you need for each situation.

在 CSS 中居中是一件很痛苦的事情。似乎有无数种方法可以做到这一点,这取决于多种因素。这将整合它们并为您提供每种情况所需的代码。

Using Flexbox

使用弹性盒

Inline with keeping this post up to date with the latest tech, here's a much easier way to center something using Flexbox. Flexbox isn't supported in Internet Explorer 9 and lower.

为了让这篇文章与最新技术保持同步,这里有一种更简单的方法来使用 Flexbox 将内容居中。Internet Explorer 9 及更低版本不支持 Flexbox 。

Here are some great resources:

这里有一些很棒的资源:

JSFiddle with browser prefixes

带有浏览器前缀的 JSFiddle

li {
  display: flex;
  justify-content: center;
  align-content: center;
  flex-direction: column;
  /* Column | row */
}
<ul>
  <li>
    <p>Some Text</p>
  </li>
  <li>
    <p>A bit more text that goes on two lines</p>
  </li>
  <li>
    <p>Even more text that demonstrates how lines can span multiple lines</p>
  </li>
</ul>

Another solution

另一种解决方案

This is from zerosixthreeand lets you center anything with six lines of CSS

这是从zerosixthree 开始,让你用六行 CSS 居中

This method isn't supported in Internet Explorer 8 and lower.

Internet Explorer 8 及更低版本不支持此方法。

jsfiddle

提琴手

p {
  text-align: center;
  position: relative;
  top: 50%;
  -ms-transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
}
<ul>
  <li>
    <p>Some Text</p>
  </li>
  <li>
    <p>A bit more text that goes on two lines</p>
  </li>
  <li>
    <p>Even more text that demonstrates how lines can span multiple lines</p>
  </li>
</ul>

Previous answer

上一个答案

A simple and cross-browser approach, useful as links in the marked answer are slightly outdated.

一种简单的跨浏览器方法,由于标记答案中的链接略有过时,因此非常有用。

How to vertically and horizontally center text in both an unordered list and a div without resorting to JavaScript or CSS line heights. No matter how much text you have you won't have to apply any special classes to specific lists or divs (the code is the same for each). This works on all major browsers including Internet Explorer 9, Internet Explorer 8, Internet Explorer 7, Internet Explorer 6, Firefox, Chrome, Operaand Safari. There are two special stylesheets (one for Internet Explorer 7 and another for Internet Explorer 6) to help them along due to their CSS limitations which modern browsers don't have.

如何在不使用 JavaScript 或 CSS 行高的情况下在无序列表和 div 中垂直和水平居中文本。无论您拥有多少文本,您都不必将任何特殊类应用于特定列表或 div(每个类的代码相同)。这适用于所有主要浏览器,包括 Internet Explorer 9、Internet Explorer 8、Internet Explorer 7、Internet Explorer 6、Firefox、Chrome、Opera和 Safari。由于现代浏览器没有的 CSS 限制,有两个特殊的样式表(一个用于 Internet Explorer 7,另一个用于 Internet Explorer 6)可以帮助它们。

Andy Howard - How to vertically and horizontally center text in an unordered list or div

Andy Howard - 如何在无序列表或 div 中垂直和水平居中文本

As I didn't care much for Internet Explorer 7/6 for the last project I worked on, I used a slightly stripped down version (i.e. removed the stuff that made it work in Internet Explorer 7 and 6). It might be useful for somebody else...

因为我在上一个项目中不太关心 Internet Explorer 7/6,所以我使用了一个稍微精简的版本(即删除了使其在 Internet Explorer 7 和 6 中工作的东西)。它可能对其他人有用......

JSFiddle

JSFiddle

.outerContainer {
  display: table;
  width: 100px;
  /* Width of parent */
  height: 100px;
  /* Height of parent */
  overflow: hidden;
}

.outerContainer .innerContainer {
  display: table-cell;
  vertical-align: middle;
  width: 100%;
  margin: 0 auto;
  text-align: center;
}

li {
  background: #ddd;
  width: 100px;
  height: 100px;
}
<ul>
  <li>
    <div class="outerContainer">
      <div class="innerContainer">
        <div class="element">
          <p>
            <!-- Content -->
            Content
          </p>
        </div>
      </div>
    </div>
  </li>

  <li>
    <div class="outerContainer">
      <div class="innerContainer">
        <div class="element">
          <p>
            <!-- Content -->
            Content
          </p>
        </div>
      </div>
    </div>
  </li>
</ul>

回答by Raul Fernandez Marques

It is easy with display: flex. With the following method, the text in the divwill be centered vertically:

使用 很容易display: flex。使用以下方法,中的文本div将垂直居中:

div {
  display: -webkit-flex;
  display: flex;
  align-items: center;
  /* More style: */
  height: 300px;
  background-color: #888;
}
<div>
  Your text here.
</div>

And if you want, horizontal:

如果你愿意,水平:

div {
  display: -webkit-flex;
  display: flex;
  align-items: center;
  justify-content: center;
  /* More style: */
  height: 300px;
  background-color: #888;
}
<div>
  Your text here.
</div>

You must see the browser version you need; in old versions the code doesn't work.

您必须看到您需要的浏览器版本;在旧版本中,代码不起作用。

回答by Stefan van den Akker

I use the following to vertically center random elements easily:

我使用以下方法轻松地垂直居中随机元素:

HTML:

HTML:

<div style="height: 200px">
    <div id="mytext">This is vertically aligned text within a div</div>
</div>

CSS:

CSS:

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

This centers the text in my divto the exact vertical middle of a 200px-high outer div. Note that you may need to use a browser prefix (like -webkit-in my case) to make this work for your browser.

这将 my 中的文本div居中到 200px 高外层的垂直中间div。请注意,您可能需要使用浏览器前缀(如-webkit-我的情况)才能使此功能适用于您的浏览器。

This works not only for text, but also for other elements.

这不仅适用于文本,也适用于其他元素。

回答by Shadrack B. Orina

You can do this by setting the display to 'table-cell' and applying a vertical-align: middle;:

您可以通过将显示设置为 'table-cell' 并应用一个来做到这一点vertical-align: middle;

    {
        display: table-cell;
        vertical-align: middle;
    }

This is however not supported by all versions of Internet Explorer according to this excerpt I copied from http://www.w3schools.com/cssref/pr_class_display.aspwithout permission.

然而,根据我未经许可从http://www.w3schools.com/cssref/pr_class_display.asp复制的这段摘录,并非所有版本的 Internet Explorer 都支持这一点。

Note:The values "inline-table", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", "table-row-group", and "inherit" are not supported by Internet Explorer 7 and earlier. Internet Explorer 8 requires a !DOCTYPE. Internet Explorer 9 supports the values.

注意:值 "inline-table", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", "table-row Internet Explorer 7 及更早版本不支持 -group”和“inherit”。Internet Explorer 8 需要 !DOCTYPE。Internet Explorer 9 支持这些值。

The following table shows the allowed display values also from http://www.w3schools.com/cssref/pr_class_display.asp.

下表也显示了http://www.w3schools.com/cssref/pr_class_display.asp 中允许的显示值。

Enter image description here

在此处输入图片说明

回答by Toni Michel Caubet

These days (we don't need Internet Explorer 6-7-8 any more) I would just use CSS display: tablefor this issue (or display: flex).

这些天(我们不再需要 Internet Explorer 6-7-8)我只会使用 CSSdisplay: table来解决这个问题(或display: flex)。



For older browsers:

对于旧浏览器:

Table:

桌子:

.vcenter {
    display: table;
    background: #eee; /* optional */
    width: 150px;
    height: 150px;
    text-align: center; /* optional */
}

.vcenter > :first-child {
    display: table-cell;
    vertical-align: middle;
}
<div class="vcenter">
  <p>This is my Text</p>
</div>

Flex:

柔性:

.vcenter {
    display: flex; /* <-- Here */
    align-items: center; /* <-- Here */
    justify-content: center; /* optional */
    height: 150px; /* <-- Here */
    background: #eee;  /* optional */
    width: 150px;
}
<div class="vcenter">
  <p>This is my text</p>
</div>



This is (actually, was) my favorite solution for this issue (simple and very well browser supported):

这是(实际上,是)我最喜欢的解决此问题的解决方案(简单且支持良好的浏览器):

div {
    margin: 5px;
    text-align: center;
    display: inline-block;
}

.vcenter {
    background: #eee;  /* optional */
    width: 150px;
    height: 150px;
}
.vcenter:before {
    content: " ";
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    max-width: 0.001%; /* Just in case the text wrapps, you shouldn't notice it */
}

.vcenter > :first-child {
    display: inline-block;
    vertical-align: middle;
    max-width: 99.999%;
}
<div class="vcenter">
  <p>This is my text</p>
</div>
<div class="vcenter">
  <h4>This is my Text<br/>Text<br/>Text</h4>
</div>
<div class="vcenter">
  <div>
   <p>This is my</p>
   <p>Text</p>
  </div>
</div>

回答by Kerim092

Try this, add on the parent div:

试试这个,在父div上添加:

display: flex;
align-items: center;

回答by Nikit Barochiya

<!DOCTYPE html>
<html>

  <head>
    <style>
      .container {
        height: 250px;
        background: #f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-align: center;
        justify-content: center;
      }
      p{
        font-size: 24px;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </body>

</html>

回答by Craig

Here is a solution that works best for a single line of text.

这是一个最适合单行文本的解决方案。

It can also work for multi-lined text with some tweaking if the number of lines is known.

如果行数已知,它也可以用于多行文本,并进行一些调整。

.testimonialText {
    font-size: 1em; /* Set a font size */
}
.testimonialText:before { /* Add a pseudo element */
    content: "";
    display: block;
    height: 50%;
    margin-top: -0.5em; /* Half of the font size */
}

Here is a JSFiddle.

这是一个 JSFiddle