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

发布于 2024-09-03 08:29:57 字数 984 浏览 7 评论 0原文

我正在尝试找到将文本与 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>

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.

.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>

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

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

发布评论

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

评论(30

舟遥客 2024-09-10 08:29:57

在现代浏览器中执行此操作的正确方法是使用 Flexbox。

有关详细信息,请参阅此答案

请参阅下文,了解在旧版浏览器中运行的一些旧方法。


CSS 中的垂直居中

http://www.jakpsatweb.cz/css/css- Vertical-center-solution.html

文章摘要:

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

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>

可以将旧浏览器 (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>

The correct way to do this in modern browsers is to use Flexbox.

See this answer for details.

See below for some older ways that work in older browsers.


Vertical Centering in 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-cell to center content.

A sample is also available at 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:

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>

一萌ing 2024-09-10 08:29:57

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

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

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

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

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

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

In fact, you could probably remove the height attribute altogether.

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

征﹌骨岁月お 2024-09-10 08:29:57

2024 更新

自从我在下面最初的回答以来,事情已经发生了很大的变化,我想向您指出这篇关于如何在 CSS 中居中 div 的杰出 Josh Comeau 文章的方向:

https://www.joshwcomeau.com/css/center-a-div/

很长一段时间以来,将一个元素置于其父元素的中心是一件非常棘手的事情。随着 CSS 的发展,我们获得了越来越多的工具来解决这个问题。这些天,我们的选择太多了!

我决定创建本教程来帮助您了解不同方法之间的权衡,并为您提供一系列可以使用的策略,以处理各种场景中的居中问题。

PS 他还有一些很棒的学习资源 CSS FlexboxCSS 网格

原始答案

这里是很棒的资源

来自http://howtocenterincss.com/

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

使用 Flexbox

Inline 并保持这篇文章与最新技术保持同步,这是一种使用 Flexbox 居中某些内容的更简单的方法。 Internet Explorer 9 及更低版本不支持 Flexbox。

以下是一些很棒的资源:

带有浏览器前缀的 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>

另一个解决方案

这是来自zerosixthird 并允许您使用六行 CSS 将任何内容居中

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>

先前的答案

一种简单且跨浏览器的方法,非常有用,因为标记答案中的链接稍微过时了。

如何在无序列表和 div 中垂直和水平居中文本,而无需借助 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 - 如何在无序列表或 div 中垂直和水平居中文本

作为对于我从事的最后一个项目,我不太关心 Internet Explorer 7/6,我使用了一个稍微精简的版本(即删除了使其在 Internet Explorer 7 和 6 中工作的内容)。它可能对其他人有用...

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>

2024 Update

Things have moved on a lot since my original answer below, and I want to point you in the direction of this exceptional Josh Comeau article on how to center a div in CSS:

https://www.joshwcomeau.com/css/center-a-div/

For a long time, centering an element within its parent was a surprisingly tricky thing to do. As CSS has evolved, we've been granted more and more tools we can use to solve this problem. These days, we're spoiled for choice!

I decided to create this tutorial to help you understand the trade-offs between different approaches, and to give you an arsenal of strategies you can use, to handle centering in all sorts of scenarios.

P.S. he also has some great resources for learning CSS Flexbox and CSS Grid

Original answer

Here's a great resource

From 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.

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.

Here are some great resources:

JSFiddle with browser prefixes

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 zerosixthree and lets you center anything with six lines of CSS

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

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, Opera and 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.

Andy Howard - How to vertically and horizontally center text in an unordered list or 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...

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>

清眉祭 2024-09-10 08:29:57

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

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

如果你愿意的话,水平:

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

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

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

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.

笑,眼淚并存 2024-09-10 08:29:57

我使用以下内容轻松垂直居中随机元素:

HTML:

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

CSS:

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

这将我的 div 中的文本居中到 200px 高的外部 div 的垂直中间位置。请注意,您可能需要使用浏览器前缀(例如我的例子中的 -webkit-)才能使其适用于您的浏览器。

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

I use the following to vertically center random elements easily:

HTML:

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

CSS:

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

This centers the text in my div to 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.

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

将军与妓 2024-09-10 08:29:57

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

display: flex;
align-items: center;

Try this, add on the parent div:

display: flex;
align-items: center;
少女情怀诗 2024-09-10 08:29:57

您可以通过将显示设置为“table-cell”并应用 vertical-align: middle; 来实现此目的:

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

但是,根据我从 < 复制的摘录,并非所有版本的 Internet Explorer 都支持此功能。 a href="http://www.w3schools.com/cssref/pr_class_display.asp/%22w3%20schools%22" rel="noreferrer">http://www.w3schools.com/cssref/pr_class_display.asp 未经许可。

注意:值“inline-table”、“table”、“table-caption”、“table-cell”、“table-column”、“table-column-group”、“table- Internet Explorer 7 及更早版本不支持“行”、“表行组”和“继承”。 Internet Explorer 8 需要 !DOCTYPE。 Internet Explorer 9 支持这些值。

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

在此处输入图像描述

You can do this by setting the display to 'table-cell' and applying a 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.asp without permission.

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.

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

Enter image description here

睡美人的小仙女 2024-09-10 08:29:57

如今(我们不再需要 Internet Explorer 6-8)我只会使用 CSS display: table 来解决此问题(或 display: flex)。

桌子:

.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>

弹性:

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


对于较旧的浏览器:

这是(实际上是)我最喜欢的解决方案(简单且浏览器支持非常好):

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>

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

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; 
    align-items: center; 
    height: 150px;
    justify-content: center; /* optional */
    background: #eee;  /* optional */
    width: 150px;
}
<div class="vcenter">
  <p>This is my text</p>
</div>


For older browsers:

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>

仙女 2024-09-10 08:29:57

Flexbox 非常适合我,将多个元素集中在父 div 内水平和垂直。

下面的代码将parent-div内的所有元素堆叠在一列中,使元素水平居中并居中。垂直。
我使用 child-div 将两个 Anchor 元素保持在同一行(行)上。如果没有 child-div,所有三个元素(Anchor、Anchor 和 Paragraph)都会堆叠在parent-div 的列内,彼此堆叠。这里只有 child-div 堆叠在parent-div 列内。

.parent-div {
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: pink;
}
<div class="parent-div">
  <div class="child-div">
    <a class="footer-link" href="https://www.github.com/">GitHub</a>
    <a class="footer-link" href="https://www.facebook.com/">Facebook</a>
    <p class="footer-copywrite">© 2019 Lorem Ipsum.</p>
  </div>
</div>

Flexbox worked perfectly for me, centering multiple elements inside parent div horizontally & vertically.

Code below stacks all elements inside of parent-div in a column, centering the elements horizontally & vertically.
I used the child-div to keep the two Anchor elements on same line (row). Without child-div all three elements (Anchor, Anchor & Paragraph) are stacked inside parent-div's column on top of each other. Here only child-div is stacked inside parent-div column.

.parent-div {
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  background: pink;
}
<div class="parent-div">
  <div class="child-div">
    <a class="footer-link" href="https://www.github.com/">GitHub</a>
    <a class="footer-link" href="https://www.facebook.com/">Facebook</a>
    <p class="footer-copywrite">© 2019 Lorem Ipsum.</p>
  </div>
</div>

相思故 2024-09-10 08:29:57

您可以使用显示网格和放置项目中心:

.container {
  width: 200px;
  height: 200px;
  border: solid red;
  display: grid;
  place-items: center;
}
<div class="container">
  Lorem, ipsum dolor.
</div>

You can use display grid and place-items center:

.container {
  width: 200px;
  height: 200px;
  border: solid red;
  display: grid;
  place-items: center;
}
<div class="container">
  Lorem, ipsum dolor.
</div>

西瑶 2024-09-10 08:29:57

非常非常简单的解决方案,我在项目中多次使用它:

源代码

.welcome_box{
    height: 300px;
    display: flex;
    justify-content: center;
    align-content: center;
    flex-direction: column;
    border: solid 1px #dadada;
}

<div class="welcome_box">Hello Friends</div>

输出:

在此处输入图像描述

感谢您提出这个问题。乐于分享。

Very very simple solution, I used it in my projects many times which is:

Source Code

.welcome_box{
    height: 300px;
    display: flex;
    justify-content: center;
    align-content: center;
    flex-direction: column;
    border: solid 1px #dadada;
}

<div class="welcome_box">Hello Friends</div>

Output:

enter image description here

Thanks to ask this question. Happy to share.

小鸟爱天空丶 2024-09-10 08:29:57

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

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

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

这是一个 JSFiddle

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.

抹茶夏天i‖ 2024-09-10 08:29:57
<!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>
<!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>
眸中客 2024-09-10 08:29:57

您可以使用 Flexbox 在 div 内垂直居中对齐文本。

<div>
   <p class="testimonialText">This is the testimonial text.</p>
</div>

div {
   display: flex;
   align-items: center;
}

您可以在Flexbox 完整指南了解更多信息

You can align center text vertically inside a div using Flexbox.

<div>
   <p class="testimonialText">This is the testimonial text.</p>
</div>

div {
   display: flex;
   align-items: center;
}

You can learn more about it at A Complete Guide to Flexbox.

ヅ她的身影、若隐若现 2024-09-10 08:29:57

检查这个简单的解决方案:

HTML

<div class="block-title"><h3>I'm a vertically centered element</h3></div>

CSS

.block-title {
    float: left;
    display: block;
    width: 100%;
    height: 88px
}

.block-title h3 {
    display: table-cell;
    vertical-align: middle;
    height: inherit
}

JSFiddle

Check this simple solution:

HTML

<div class="block-title"><h3>I'm a vertically centered element</h3></div>

CSS

.block-title {
    float: left;
    display: block;
    width: 100%;
    height: 88px
}

.block-title h3 {
    display: table-cell;
    vertical-align: middle;
    height: inherit
}

JSFiddle

心是晴朗的。 2024-09-10 08:29:57

这是我找到的最干净的解决方案(Internet Explorer 9+),并通过使用其他答案省略的 transform-style 添加了“关闭 0.5 像素”问题的修复。

.parent-element {
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.element {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

来源:垂直对齐仅 3 的任何内容CSS 行

This is the cleanest solution I have found (Internet Explorer 9+) and adds a fix for the "off by .5 pixel" issue by using transform-style that other answers had omitted.

.parent-element {
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.element {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

Source: Vertical align anything with just 3 lines of CSS

呆° 2024-09-10 08:29:57

HTML:

<div class="col-md-2 ml-2 align-middle">
    <label for="option2" id="time-label">Time</label>
</div>

CSS:

.align-middle {
    margin-top: auto;
    margin-bottom: auto;
}

HTML :

<div class="col-md-2 ml-2 align-middle">
    <label for="option2" id="time-label">Time</label>
</div>

CSS :

.align-middle {
    margin-top: auto;
    margin-bottom: auto;
}
烟火散人牵绊 2024-09-10 08:29:57

使用 CSS 网格为我做到了:

.outer {
    background-color: grey;
    width: 10rem;
    height: 10rem;
    display: grid;
    justify-items: center;
}

.inner {
    background-color: #FF8585;
    align-self: center;
}
<div class='outer'>
    <div class='inner'>
       Content
    </div>
</div>

Using CSS grid did it for me:

.outer {
    background-color: grey;
    width: 10rem;
    height: 10rem;
    display: grid;
    justify-items: center;
}

.inner {
    background-color: #FF8585;
    align-self: center;
}
<div class='outer'>
    <div class='inner'>
       Content
    </div>
</div>

回眸一遍 2024-09-10 08:29:57

有一种更简单的方法可以垂直对齐内容,而无需借助表格/表格单元格:

http://jsfiddle.net /bBW5w/1/

在其中我添加了一个不可见的(宽度=0)div,它假定容器的整个高度。

它似乎适用于 Internet Explorer 和 Firefox(最新版本)。我没有检查其他浏览器

  <div class="t">
     <div>
         everything is vertically centered in modern IE8+ and others.
     </div>
      <div></div>
   </div>

当然还有CSS:

.t, .t > div:first-child
{
    border: 1px solid green;
}
.t
{
    height: 400px;
}
.t > div
{
    display: inline-block;
    vertical-align: middle
}
.t > div:last-child
{
    height: 100%;
}

There's a simpler way to vertically align the content without resorting to table/table-cell:

http://jsfiddle.net/bBW5w/1/

In it I have added an invisible (width=0) div that assumes the entire height of the container.

It seems to work in Internet Explorer and Firefox (latest versions). I didn't check with other browsers

  <div class="t">
     <div>
         everything is vertically centered in modern IE8+ and others.
     </div>
      <div></div>
   </div>

And of course the CSS:

.t, .t > div:first-child
{
    border: 1px solid green;
}
.t
{
    height: 400px;
}
.t > div
{
    display: inline-block;
    vertical-align: middle
}
.t > div:last-child
{
    height: 100%;
}
雪若未夕 2024-09-10 08:29:57

解决不知道值的元素的简单方法:

HTML

<div class="main">
    <div class="center">
        whatever
    </div>
</div>

CSS

.main {
    position: relative
}

.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
}

A simple solution to an element of not knowing values:

HTML

<div class="main">
    <div class="center">
        whatever
    </div>
</div>

CSS

.main {
    position: relative
}

.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
}
何止钟意 2024-09-10 08:29:57

根据 Adam Tomat 的回答,准备了一个 JSFiddle 示例 对齐 div 中的文本:

<div class="cells-block">    
    text<br/>in the block   
</div>

通过在 CSS 中使用 display:flex

.cells-block {
    display: flex;
    flex-flow: column;
    align-items: center;       /* Vertically   */
    justify-content: flex-end; /* Horisontally */
    text-align: right;         /* Addition: for text's lines */
}

与另一个 示例以及博客文章

According to Adam Tomat's answer there was prepared a JSFiddle example to align the text in div:

<div class="cells-block">    
    text<br/>in the block   
</div>

by using display:flex in CSS:

.cells-block {
    display: flex;
    flex-flow: column;
    align-items: center;       /* Vertically   */
    justify-content: flex-end; /* Horisontally */
    text-align: right;         /* Addition: for text's lines */
}

with another example and a few explanations in a blog post.

腹黑女流氓 2024-09-10 08:29:57

网格项上的自动边距。

与 Flexbox 类似,在网格项上应用 margin auto 使其在两个轴上居中:

.container {
  display: grid;
}
.element {
  margin: auto;
}

Margin auto on a grid-item.

Similarly to Flexbox, applying margin auto on a grid-item centers it on both axes:

.container {
  display: grid;
}
.element {
  margin: auto;
}
梨涡少年 2024-09-10 08:29:57

使用:

h1 {
    margin: 0;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
.container {
    height: 200px;
    width: 500px;
    position: relative;
    border: 1px solid #eee;
}
<div class="container">
    <h1>Vertical align text</h1>
</div>

通过这个技巧,如果您不想使其居中,则可以对齐任何内容,添加“left:0”以左对齐。

Use:

h1 {
    margin: 0;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
.container {
    height: 200px;
    width: 500px;
    position: relative;
    border: 1px solid #eee;
}
<div class="container">
    <h1>Vertical align text</h1>
</div>

With this trick, you can align anything if you don't want to make it center add "left:0" to align left.

丶情人眼里出诗心の 2024-09-10 08:29:57

HTML

<div class="relative"><!--used as a container-->
    <!-- add content here to to make some height and width
    example:<img src="" alt=""> -->
    <div class="absolute">
        <div class="table">
            <div class="table-cell">
                Vertical contents goes here
            </div>
        </div>
    </div>
</div>

CSS

 .relative {
     position: relative;
 }
 .absolute {
     position: absolute;
     top: 0;
     bottom: 0;
     left: 0;
     right: 0;
     background: rgba(0, 0, 0, 0.5);
 }
 .table {
     display: table;
     height: 100%;
     width: 100%;
     text-align: center;
     color: #fff;
 }
 .table-cell {
     display: table-cell;
     vertical-align: middle;
 }

HTML

<div class="relative"><!--used as a container-->
    <!-- add content here to to make some height and width
    example:<img src="" alt=""> -->
    <div class="absolute">
        <div class="table">
            <div class="table-cell">
                Vertical contents goes here
            </div>
        </div>
    </div>
</div>

CSS

 .relative {
     position: relative;
 }
 .absolute {
     position: absolute;
     top: 0;
     bottom: 0;
     left: 0;
     right: 0;
     background: rgba(0, 0, 0, 0.5);
 }
 .table {
     display: table;
     height: 100%;
     width: 100%;
     text-align: center;
     color: #fff;
 }
 .table-cell {
     display: table-cell;
     vertical-align: middle;
 }
执笏见 2024-09-10 08:29:57

使用 flex 时,请注意浏览器渲染的差异。

这对于 Chrome 和 Internet Explorer 都很有效:

.outer {
    display: flex;
    width: 200px;
    height: 200px;
    background-color: #ffc;
}

.inner {
    display: flex;
    width: 50%;
    height: 50%;
    margin: auto;
    text-align: center;
    justify-content: center;
    align-items: center;
    background-color: #fcc;
}
<div class="outer"><div class="inner">Active Tasks</div></div>

与仅适用于 Chrome 的这个进行比较:

.outer {
    display: flex;
    width: 200px;
    height: 200px;
    background-color: #ffc;
}

.inner {
    display: flex;
    width: 50%;
    height: 50%;
    margin: auto;
    background-color: #fcc;
}
<div class="outer">
<div class="inner"><span style=" margin: auto;">Active Tasks</span></div>
</div>

Using flex, be careful with differences in browsers' rendering.

This works well both for Chrome and Internet Explorer:

.outer {
    display: flex;
    width: 200px;
    height: 200px;
    background-color: #ffc;
}

.inner {
    display: flex;
    width: 50%;
    height: 50%;
    margin: auto;
    text-align: center;
    justify-content: center;
    align-items: center;
    background-color: #fcc;
}
<div class="outer"><div class="inner">Active Tasks</div></div>

Compare with this one that works only with Chrome:

.outer {
    display: flex;
    width: 200px;
    height: 200px;
    background-color: #ffc;
}

.inner {
    display: flex;
    width: 50%;
    height: 50%;
    margin: auto;
    background-color: #fcc;
}
<div class="outer">
<div class="inner"><span style=" margin: auto;">Active Tasks</span></div>
</div>

热血少△年 2024-09-10 08:29:57

2024

浏览器现已添加对 align-content 上的代码>(即使用 display:block 设置)。经过这么多年,您终于可以使用两个简单的 CSS 属性来做到这一点:

.centered-content {
  align-content: center;   /* centers vertically */
  text-align: center;      /* centers horizontally */
}
<div class="centered-content" style="height:200px; background:silver">Hello World!</div>

此解决方案的一个很酷的优点是您可以使用 text-overflow: ellipsis 而无需向

添加子项。

浏览器支持:Chrome 123、Edge 123、Firefox 125、Safari 17.4

2024

Browsers now added support for align-content on a default <div> (i.e. set with display:block). So after all these years you can finally do this with two simple CSS properties:

.centered-content {
  align-content: center;   /* centers vertically */
  text-align: center;      /* centers horizontally */
}
<div class="centered-content" style="height:200px; background:silver">Hello World!</div>

A cool advantage of this solution is that you can use text-overflow: ellipsis without adding a child to your <div>.

Browser Support: Chrome 123, Edge 123, Firefox 125, Safari 17.4

原谅过去的我 2024-09-10 08:29:57

这是在 CSS 中使用 calc()div 模式中 div 的另一种变体。

<div style="height:300px; border:1px solid green;">
  Text in outer div.
  <div style="position:absolute; height:20px; top:calc(50% - 10px); border:1px solid red;)">
    Text in inner div.
  </div>
</div>

这是可行的,因为:

  • position:absolute 为了在 div 中精确放置 div
  • 我们知道内部 div 因为我们将其设置为 20px
  • calc(50% - 10px) 表示 50% - 高度的一半,用于使内部 div 居中

This is another variation of the div in a div pattern using calc() in CSS.

<div style="height:300px; border:1px solid green;">
  Text in outer div.
  <div style="position:absolute; height:20px; top:calc(50% - 10px); border:1px solid red;)">
    Text in inner div.
  </div>
</div>

This works, because:

  • position:absolute for precise placement of the div within a div
  • we know the height of the inner div because we set it to 20px.
  • calc(50% - 10px) for 50% - half the height for centering the inner div
灯下孤影 2024-09-10 08:29:57

这工作正常:

HTML

<div class="information">
    <span>Some text</span>
    <mat-icon>info_outline</mat-icon>
</div>

Sass

.information {
    display: inline-block;
    padding: 4px 0;
    span {
        display: inline-block;
        vertical-align: middle;
    }
    mat-icon {
        vertical-align: middle;
    }
}

不带和带图像标签 (这是一种字体)。

This works fine:

HTML

<div class="information">
    <span>Some text</span>
    <mat-icon>info_outline</mat-icon>
</div>

Sass

.information {
    display: inline-block;
    padding: 4px 0;
    span {
        display: inline-block;
        vertical-align: middle;
    }
    mat-icon {
        vertical-align: middle;
    }
}

Without and with the image tag <mat-icon> (which is a font).

别在捏我脸啦 2024-09-10 08:29:57

您可以使用 css flexbox

.testimonialText {
  height: 500px;
  padding: 1em;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #b4d2d2;
}
<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>

You can use css flexbox.

.testimonialText {
  height: 500px;
  padding: 1em;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #b4d2d2;
}
<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>

土豪我们做朋友吧 2024-09-10 08:29:57

这将使文本垂直居中:

.parent {
  display: inline-flex
}

.testimonialText {
  margin-top: auto;
  margin-bottom: auto;
}
<div class="parent">
  <div class="testimonialText">
    Hello World
  </div>
</div>

This will center text vertically:

.parent {
  display: inline-flex
}

.testimonialText {
  margin-top: auto;
  margin-bottom: auto;
}
<div class="parent">
  <div class="testimonialText">
    Hello World
  </div>
</div>

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