简体   繁体   English

如何在 div 块内居中文本(水平和垂直)?

[英]How can I center text (horizontally and vertically) inside a div block?

I have a div set to display:block ( 90px height and width ), and I have some text inside.我有一个div设置为display:block90px heightwidth ),我里面有一些文本。

I need the text to be aligned in the center both vertically and horizontally.我需要将文本垂直和水平对齐在中心。

I have tried text-align:center , but it doesn't do the vertical centering part, so I tried vertical-align:middle , but it didn't work.我试过text-align:center ,但它没有做垂直居中部分,所以我尝试了vertical-align:middle ,但它没有用。

Any ideas?有任何想法吗?

If it is one line of text and/or image, then it is easy to do.如果它是一行文本和/或图像,那么很容易做到。 Just use:只需使用:

text-align: center;
vertical-align: middle;
line-height: 90px;       /* The same as your div height */

That's it.而已。 If it can be multiple lines, then it is somewhat more complicated.如果它可以是多行,那么它会更复杂一些。 But there are solutions on http://pmob.co.uk/ .但是http://pmob.co.uk/上有解决方案。 Look for "vertical align".寻找“垂直对齐”。

Since they tend to be hacks or adding complicated divs... I usually use a table with a single cell to do it... to make it as simple as possible.因为它们往往是黑客或添加复杂的 div... 我通常使用一个带有单个单元格的表格来完成它... 使其尽可能简单。


Update for 2020: 2020 年更新:

Unless you need make it work on earlier browsers such as Internet Explorer 10, you can use flexbox.除非您需要让它在 Internet Explorer 10 等早期浏览器上工作,否则您可以使用 flexbox。 It is widely supported by all current major browsers .目前所有主流浏览器都广泛支持它。 Basically, the container needs to be specified as a flex container, together with centering along its main and cross axis:基本上,需要将容器指定为 flex 容器,并沿其主轴和交叉轴居中:

#container {
  display: flex;
  justify-content: center;
  align-items: center;
}

To specify a fixed width for the child, which is called a "flex item":为孩子指定一个固定的宽度,称为“弹性项目”:

#content {
  flex: 0 0 120px;
}

Example: http://jsfiddle.net/2woqsef1/1/示例:http: //jsfiddle.net/2woqsef1/1/

To shrink-wrap the content, it is even simpler: just remove the flex: ... line from the flex item, and it is automatically shrink-wrapped.要收缩包装内容,它更简单:只需从 flex 项目中删除flex: ...行,它就会自动收缩包装。

Example: http://jsfiddle.net/2woqsef1/2/示例:http: //jsfiddle.net/2woqsef1/2/

The examples above have been tested on major browsers including MS Edge and Internet Explorer 11.上面的示例已经在包括 MS Edge 和 Internet Explorer 11 在内的主要浏览器上进行了测试。

One technical note if you need to customize it: inside of the flex item, since this flex item is not a flex container itself, the old non-flexbox way of CSS works as expected.如果您需要对其进行自定义,请提供一个技术说明:在 flex 项目内部,由于此 flex 项目本身不是 flex 容器,因此旧的非 flexbox 方式的 CSS 可以按预期工作。 However, if you add an additional flex item to the current flex container, the two flex items will be horizontally placed.然而,如果你在当前的 flex 容器中添加一个额外的 flex 项,这两个 flex 项将被水平放置。 To make them vertically placed, add the flex-direction: column;要使它们垂直放置,请添加flex-direction: column; to the flex container.到弹性容器。 This is how it works between a flex container and its immediate child elements.这就是它在 flex 容器及其直接子元素之间的工作方式。

There is an alternative method of doing the centering: by not specifying center for the distribution on the main and cross axis for the flex container, but instead specify margin: auto on the flex item to take up all extra space in all four directions, and the evenly distributed margins will make the flex item centered in all directions.还有另一种进行居中的方法:不为 flex 容器的主轴和交叉轴上的分布指定center ,而是在 flex 项目上指定margin: auto以占用所有四个方向上的所有额外空间,并且均匀分布的边距将使弹性项目在所有方向上居中。 This works except when there are multiple flex items.这有效,除非有多个弹性项目。 Also, this technique works on MS Edge but not on Internet Explorer 11.此外,此技术适用于 MS Edge,但不适用于 Internet Explorer 11。


Update for 2016 / 2017: 2016 / 2017 年更新:

It can be more commonly done with transform , and it works well even in older browsers such as Internet Explorer 10 and Internet Explorer 11. It can support multiple lines of text:它可以更常见地使用transform完成,即使在 Internet Explorer 10 和 Internet Explorer 11 等较旧的浏览器中也能很好地工作。它可以支持多行文本:

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

Example: https://jsfiddle.net/wb8u02kL/1/示例: https ://jsfiddle.net/wb8u02kL/1/

To shrink-wrap the width:要收缩包装宽度:

The solution above used a fixed width for the content area.上面的解决方案对内容区域使用了固定宽度。 To use a shrink-wrapped width, use要使用收缩包装的宽度,请使用

position: relative;
float: left;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Example: https://jsfiddle.net/wb8u02kL/2/示例: https ://jsfiddle.net/wb8u02kL/2/

If the support for Internet Explorer 10 is needed, then flexbox won't work and the method above and the line-height method would work.如果需要对 Internet Explorer 10 的支持,那么 flexbox 将不起作用,而上面的方法和line-height方法将起作用。 Otherwise, flexbox would do the job.否则,flexbox 会完成这项工作。

Common techniques as of 2014:截至 2014 年的常用技术:


  • Approach 1 - transform translateX / translateY :方法 1 - transform translateX / translateY

    Example Here / Full Screen Example此处示例/全屏示例

    In supported browsers (most of them), you can use top: 50% / left: 50% in combination with translateX(-50%) translateY(-50%) to dynamically vertically/horizontally center the element.支持的浏览器(大多数)中,您可以使用top: 50% / left: 50%结合translateX(-50%) translateY(-50%)来动态垂直/水平居中元素。

     .container { position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%); }

  • Approach 2 - Flexbox method:方法 2 - Flexbox 方法:

    Example Here / Full Screen Example此处示例/全屏示例

    In supported browsers , set the display of the targeted element to flex and use align-items: center for vertical centering and justify-content: center for horizontal centering.支持的浏览器中,将目标元素的display设置为flex并使用align-items: center垂直居中和justify-content: center水平居中。 Just don't forget to add vendor prefixes for additional browser support ( see example ).只是不要忘记添加供应商前缀以获得额外的浏览器支持(参见示例)。

     html, body, .container { height: 100%; } .container { display: flex; align-items: center; justify-content: center; }

  • Approach 3 - table-cell / vertical-align: middle :方法 3 - table-cell / vertical-align: middle

    Example Here / Full Screen Example此处示例/全屏示例

    In some cases, you will need to ensure that the html / body element's height is set to 100% .在某些情况下,您需要确保将html / body元素的高度设置为100%

    For vertical alignment, set the parent element's width / height to 100% and add display: table .对于垂直对齐,将父元素的width / height设置为100%并添加display: table Then for the child element, change the display to table-cell and add vertical-align: middle .然后对于子元素,将display更改为table-cell并添加vertical-align: middle

    For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.对于水平居中,您可以添加text-align: center以使文本和任何其他inline子元素居中。 Alternatively, you could use margin: 0 auto assuming the element is block level.或者,您可以使用margin: 0 auto假设元素是block级的。

     html, body { height: 100%; } .parent { width: 100%; height: 100%; display: table; text-align: center; } .parent > .child { display: table-cell; vertical-align: middle; }

  • Approach 4 - Absolutely positioned 50% from the top with displacement:方法 4 - 从顶部绝对定位50% ,有位移:

    Example Here / Full Screen Example此处示例/全屏示例

    This approach assumes that the text has a known height - in this instance, 18px .这种方法假定文本具有已知的高度 - 在本例中为18px Just absolutely position the element 50% from the top, relative to the parent element.相对于父元素,将元素从顶部绝对定位50% Use a negative margin-top value that is half of the element's known height, in this case - -9px .使用元素已知高度的一半的负margin-top值,在本例中-9px

     html, body, .container { height: 100%; } .container { position: relative; text-align: center; } .container > p { position: absolute; top: 50%; left: 0; right: 0; margin-top: -9px; }

  • Approach 5 - The line-height method (Least flexible - not suggested):方法 5 - line-height方法(最不灵活 - 不建议):

    Example Here示例在这里

    In some cases, the parent element will have a fixed height.在某些情况下,父元素将具有固定的高度。 For vertical centering, all you have to do is set a line-height value on the child element equal to the fixed height of the parent element.对于垂直居中,您所要做的就是在子元素上设置一个等于父元素的固定高度的line-height值。

    Though this solution will work in some cases, it's worth noting that it won't work when there are multiple lines of text - like this .尽管此解决方案在某些情况下会起作用,但值得注意的是,当有多行文本时它不起作用 -像 this

     .parent { height: 200px; width: 400px; text-align: center; } .parent > .child { line-height: 200px; }

Methods 4 and 5 aren't the most reliable.方法 4 和 5 不是最可靠的。 Go with one of the first 3.选择前 3 个中的一个。

Using flexbox/CSS:使用弹性盒/CSS:

<div class="box">
    <p>&#x0D05;</p>
</div>

The CSS: CSS:

.box{
    display: flex;
    justify-content: center;
    align-items: center;
}

Taken from Quick Tip: The Simplest Way To Center Elements Vertically And Horizontally取自快速提示:垂直和水平居中元素的最简单方法

Add the line display: table-cell;添加行display: table-cell; to your CSS content for that div.到该 div 的 CSS 内容。

Only table cells support the vertical-align: middle;只有表格单元格支持vertical-align: middle; , but you can give that [table-cell] definition to the div... ,但是您可以将 [table-cell] 定义赋予 div ...

A live example is here: http://jsfiddle.net/tH2cc/一个活生生的例子在这里:http: //jsfiddle.net/tH2cc/

div{
    height: 90px;
    width: 90px;
    text-align: center;
    border: 1px solid silver;
    display: table-cell; // This says treat this element like a table cell
    vertical-align:middle; // Now we can center vertically like in a TD
}

Give this CSS class to the targeted <div>:将此 CSS 类赋予目标 <div>:

 .centered { width: 150px; height: 150px; display: flex; align-items: center; justify-content: center; text-align: center; background: red; /* Not necessary just to see the result clearly */ }
 <div class="centered">This text is centered horizontally and vertically</div>

You can try very easy code for this:您可以为此尝试非常简单的代码:

  display: flex;
  align-items: center;
  justify-content: center;

 .box{ height: 90px; width: 90px; background: green; display: flex; align-items: center; justify-content: center; }
 <div class="box"> Lorem </div>

Codepen link: http://codepen.io/santoshkhalse/pen/xRmZwr Codepen 链接: http ://codepen.io/santoshkhalse/pen/xRmZwr

I always use the following CSS for a container, to center its content horizontally and vertically.我总是使用以下 CSS 作为容器,使其内容水平和垂直居中。

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;

-webkit-box-align: center;
-moz-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;

-webkit-box-pack: center;
-moz-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;

See it in action here: https://jsfiddle.net/yp1gusn7/在此处查看实际操作: https ://jsfiddle.net/yp1gusn7/

You can use the flex property at the parent div and add the margin:auto property to the children items:您可以在div中使用flex属性并将margin:auto属性添加到子项:

.parent {
    display: flex;
    /* You can change this to `row` if you want the items side by side instead of stacked */
    flex-direction: column;
}

/* Change the `p` tag to what your items child items are */
.parent p {
    margin: auto;
}

You can see more options of flex here: https://css-tricks.com/snippets/css/a-guide-to-flexbox/你可以在这里看到更多的flex选项: https ://css-tricks.com/snippets/css/a-guide-to-flexbox/

2020 Way 2020年的方式

.parent{ 
  display: grid;
  place-items: center;
}

Approach 1方法一

 div { height: 90px; line-height: 90px; text-align: center; border: 2px dashed #f69c55; }
 <div> Hello, World!! </div>

Approach 2方法二

 div { height: 200px; line-height: 200px; text-align: center; border: 2px dashed #f69c55; } span { display: inline-block; vertical-align: middle; line-height: normal; }
 <div> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Haec et tu ita posuisti, et verba vestra sunt. Non enim iam stirpis bonum quaeret, sed animalis. </span> </div>

Approach 3方法 3

 div { display: table; height: 100px; width: 100%; text-align: center; border: 2px dashed #f69c55; } span { display: table-cell; vertical-align: middle; }
 <div> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> </div>

# Parent
{
  display:table;
}

# Child
{
  display: table-cell;
  width: 100%; // As large as its parent to center the text horizontally
  text-align: center;
  vertical-align: middle; // Vertically align this element on its parent
}

Add the following code in the parent div在父div中添加以下代码

 display: grid;
 place-items: center;
<div class="small-container">
    <span>Text centered</span>
</div>

<style>
.small-container {
    width:250px;
    height:250px;
    border:1px green solid;
    text-align:center;
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
.small-container span{
    position: absolute;
    top: 50%;
    left: 50%;
    -moz-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
}
</style>

 div { height: 90px; line-height: 90px; text-align: center; border: 2px dashed #f69c55; }
 <div> Hello, World!! </div>

GRID网格

.center {
    display: grid;
    justify-items: center;
    align-items: center;
}

 .center { display: grid; justify-items: center; align-items: center; } .box { width: 200px; height: 100px; background: red; }
 <div class="box center">My text</div>

调整行高以获得垂直对齐。

line-height: 90px;

This works for me (tested OK!):这对我有用(测试OK!):

HTML: HTML:

<div class="mydiv">
    <p>Item to be centered!</p>
</div>

CSS: CSS:

.mydiv {
    height: 100%; /* Or other */
    position: relative;
}

.mydiv p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%); /* To compensate own width and height */
}

You can choose other values than 50%.您可以选择 50% 以外的其他值。 For example, 25% to center at 25% of parent.例如,25% 以父母的 25% 为中心。

You can try the following methods:您可以尝试以下方法:

  1. If you have a single word or one line sentence, then the following code can do the trick.如果您只有一个单词或一行句子,那么下面的代码就可以解决问题。

    Have a text inside a div tag and give it an id.在 div 标签内有一个文本并给它一个 id。 Define the following properties for that id.为该 ID 定义以下属性。

     id-name { height: 90px; line-height: 90px; text-align: center; border: 2px dashed red; }

    Note: Make sure the line-height property is same as the height of the division.注意:确保 line-height 属性与分割的高度相同。

    Image图片

    But, if the content is more than one single word or a line then this doesn't work.但是,如果内容超过一个单词或一行,那么这不起作用。 Also, there will be times when you cannot specify the size of a division in px or % (when the division is really small and you want the content to be exactly in the middle).此外,有时您无法以 px 或 % 为单位指定分区的大小(当分区非常小并且您希望内容正好在中间时)。

  2. To solve this issue, we can try the following combination of properties.为了解决这个问题,我们可以尝试下面的属性组合。

     id-name { display: flex; justify-content: center; align-items: center; border: 2px dashed red; }

    Image图片

    These 3 lines of code sets the content exactly in the middle of a division (irrespective of the size of the display).这 3 行代码将内容准确地设置在一个分区的中间(与显示的大小无关)。 The "align-items: center" helps in vertical centering while "justify-content: center" will make it horizontally centered. “align-items:center”有助于垂直居中,而“justify-content:center”将使其水平居中。

    Note: Flex does not work in all browsers.注意: Flex 并非适用于所有浏览器。 Make sure you add appropriate vendor prefixes for additional browser support.确保添加适当的供应商前缀以获得额外的浏览器支持。

 .cell-row {display: table; width: 100%; height: 100px; background-color: lightgrey; text-align: center} .cell {display: table-cell} .cell-middle {vertical-align: middle}
 <div class="cell-row"> <div class="cell cell-middle">Center</div> </div>

Really simple code that works for me!对我有用的非常简单的代码! Just one line and your text will be centered horizontally.只需一行,您的文本将水平居中。

.center-horizontally{
  justify-content: center;
}

<Card.Footer className="card-body-padding center-horizontally">
  <label className="support-expand-text-light">Call or email Customer Support to change</label>
</Card.Footer>

The output looks like this:输出如下所示:

<!DOCTYPE html>
<html>
  <head>
    <style>
      .maindiv {
        height: 450px;
        background: #f8f8f8;
        display: -webkit-flex;
        align-items: center;
        justify-content: center;
      }
      p {
        font-size: 24px;
      }
    </style>
  </head>

  <body>
    <div class="maindiv">
      <h1>Title</h1>
    </div>
  </body>
</html>

For me this was the best solution:对我来说,这是最好的解决方案:

HTML: HTML:

 <div id="outer">  
     <img src="logo.png">
 </div>

CSS: CSS:

#outer {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

Apply style:应用风格:

position: absolute;
top: 50%;
left: 0;
right: 0;

Your text would be centered irrespective of its length.无论其长度如何,您的文本都会居中。

This worked for me:这对我有用:

.center-stuff{
    text-align: center;
    vertical-align: middle;
    line-height: 230px; /* This should be the div height */
}

This should be the right answer.这应该是正确的答案。 Cleanest and simplest:最干净和最简单的:

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
<!DOCTYPE html>
<html>
    <head>

    </head>
    <body>
        <div style ="text-align: center;">Center horizontal text</div>
        <div style ="position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%);">Center vertical text</div>
    </body>
</html> 
.container  p {display:flex;align-item:center;
justify-content: center}

Try the following example.试试下面的例子。 I have added examples for each category: horizontal and vertical我为每个类别添加了示例:水平和垂直

<!DOCTYPE html>
<html>
    <head>
        <style>
            #horizontal
            {
                text-align: center;
            }
            #vertical
            {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translateX(-50%) translateY(-50%);
            }
         </style>
    </head>
    <body>
         <div id ="horizontal">Center horizontal text</div>
         <div id ="vertical">Center vertical text</div>
    </body>
</html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM