首页 文章

使用CSS垂直居中文本

提问于
浏览
1946

我有一个包含文本的 div 元素,我想对齐 div 垂直中心的内容 .

这是我的div风格:

#box {
  height: 170px;
  width: 270px;
  background: #000;
  font-size: 48px;
  color: #FFF;
  text-align: center;
}
<div id="box">
  Lorem ipsum dolor sit
</div>

做这个的最好方式是什么?

30 回答

  • 2568

    CSS3中引入的Flexbox是解决方案:

    section {
        display: flex;
        display: -webkit-flex;
        height: 200px;
        width: 50%;
        margin: auto;
        border-radius: 20px;
        border: 3px solid orange;
        background-color: gold;
    }
    
    p {
        margin: auto; /* Important */
        text-align: center;
        font-family: Calibri;
        background-color: yellow;
        border-radius: 20px;
        padding: 15px;
    }
    
    <section>
        <p>
            I'm centered!
    Flexboxes are great! </p> </section>

    Note :如果要将文本居中,请将上面标记为重要的行替换为其中一行:

    1)仅垂直:

    margin: auto 0;
    

    2)仅横向:

    margin: 0 auto;
    

    UPDATE :正如我注意到的,这个技巧也适用于网格(显示:网格) .

  • 9

    试试this solution

    .EXTENDER {
        position: absolute;
        top: 0px;
        left: 0px;
        bottom: 0px;
        right: 0px;
        width: 100%;
        height: 100%;
        overflow-y: hidden;
        overflow-x: hidden;
    }
    
    .PADDER-CENTER {
        width: 100%;
        height: 100%;
        display: -webkit-box;
        display: -moz-box;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -webkit-box-pack: center;
        -moz-box-pack: center;
        -ms-flex-pack: center;
        -webkit-justify-content: center;
        justify-content: center;
        -webkit-box-align: center;
        -moz-box-align: center;
        -ms-flex-align: center;
        -webkit-align-items: center;
        align-items: center;
    }
    
    <div class="EXTENDER">
      <div class="PADDER-CENTER">
        <div contentEditable="true">Edit this text...</div>
      </div>
    </div>
    

    使用CSS+构建 .

  • 1

    其他方式:

    不要设置 divheight 属性,而是使用 padding: 来实现效果 . 与行高相似,只有在有一行文本时才有效 . 虽然这样,如果你有更多的内容,文本仍然会居中,但div本身会略大 .

    所以不要去:

    div {
      height:120px;
      line-height: 120px;
    }
    

    你可以说:

    div {
       padding: 60px 0; //Maybe 60 minus font-size divided by two, if you want to be  exact
    }
    

    这会将 div 的顶部和底部 padding 设置为 60px ,将左侧和右侧 padding 设置为零,使 div 120px(加上字体的高度)变高,并将文本垂直居中放置在div中 .

  • 119

    Absolute Positioning and Stretching

    与上面的方法一样,这个方法首先将父元素和子元素的定位分别设置为relative和absolute . 从那里开始有所不同 .

    在下面的代码中,我再一次使用这种方法将孩子水平和垂直居中,尽管你只能使用这种方法进行垂直居中 .

    html

    <div id="parent">
        <div id="child">Content here</div>
    </div>
    

    css

    #parent {position: relative;}
    #child {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        width: 50%;
        height: 30%;
        margin: auto;
    }
    

    使用此方法的想法是尝试通过将top,bottom,right和left vales设置为0来使子元素伸展到所有4个边缘 . 因为我们的子元素小于我们的父元素,所以它不能到达所有4个边缘 .

    将auto设置为所有4个边上的边距会导致相反的边距相等,并在父div的中心显示我们的子div .

    不幸的是,上面的内容在IE7及以下版本中不起作用,就像之前的方法一样,子div内的内容可能会变得太大而导致它被隐藏 .

  • 4

    无论您想要垂直中心样式,都可以尝试 display:table-cellvertical-align:middle .

    Example:

    #box
    {
      display: table-cell;
      vertical-align: middle;
      height: 90px;
      width: 270px;
      background: #000;
      font-size: 48px;
      font-style: oblique;
      color: #FFF;
      text-align: center;
      margin-top: 20px;
      margin-left: 5px;
    }
    
    <div Id="box">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </div>
    
  • 9

    另一种方式(此处尚未提及)是Flexbox .

    只需将以下代码添加到 container 元素:

    display: flex;
    justify-content: center; /* align horizontal */
    align-items: center; /* align vertical */
    

    Flexbox演示1

    .box {
      height: 150px;
      width: 400px;
      background: #000;
      font-size: 24px;
      font-style: oblique;
      color: #FFF;
      text-align: center;
      padding: 0 20px;
      margin: 20px;
      display: flex;
      justify-content: center;
      /* align horizontal */
      align-items: center;
      /* align vertical */
    }
    
    <div class="box">
      Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
    </div>
    

    或者,不是通过容器对齐内容,当flex容器中只有一个flex项时,flexbox也可以使 flex itemauto margin居中(如上面问题中给出的示例) .

    因此,要将flex项目水平和垂直居中,只需使用 margin:auto 进行设置即可 .

    Flexbox演示2

    .box {
      height: 150px;
      width: 400px;
      background: #000;
      font-size: 24px;
      font-style: oblique;
      color: #FFF;
      text-align: center;
      padding: 0 20px;
      margin: 20px;
      display: flex;
    }
    .box span {
      margin: auto;
    }
    
    <div class="box">
      <span>margin:auto on a flex item centers it both horizontally and vertically</span> 
    </div>
    

    NB: 以上所有内容适用于在 horizontal rows 中布置物品时对中心物品 . 这也是默认行为,因为默认情况下 flex-direction 的值为 row . 但是,如果需要在 vertical columns 中布置flex项目,则应在容器上设置 flex-direction: column 以将主轴设置为列,此外 justify-contentalign-items 属性现在以 justify-content: center 垂直居中并且 align-items: center 居中相反的方式工作水平)

    flex-direction:列演示

    .box {
      height: 150px;
      width: 400px;
      background: #000;
      font-size: 18px;
      font-style: oblique;
      color: #FFF;
      display: flex;
      flex-direction: column;
      justify-content: center;
      /* vertically aligns items */
      align-items: center;
      /* horizontally aligns items */
    }
    p {
      margin: 5px;
      }
    
    <div class="box">
      <p>
        When flex-direction is column...
      </p>
      <p>
        "justify-content: center" - vertically aligns
      </p>
      <p>
        "align-items: center" - horizontally aligns
      </p>
    </div>
    

    一个开始使用Flexbox查看其中一些功能并获得最大浏览器支持语法的好地方是flexyboxes

    此外,如今的浏览器支持非常好:caniuse

    对于 display: flexalign-items 的跨浏览器兼容性,您可以使用以下内容:

    display: -webkit-box;
    display: -webkit-flex;
    display: -moz-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-flex-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
    
  • 4
    .element{position: relative;top: 50%;transform: translateY(-50%);}
    

    在元素的CSS属性中添加这个小代码 . 太棒了 . 试试吧!

  • 2

    您还可以使用以下属性 .

    display: flex; 
    align-content: center; 
    justify-content : center;
    
  • 3

    Flexible approach

    div {
      width: 250px;
      min-height: 50px;
      line-height: 50px;
      text-align: center;
      border: 1px solid #123456;
      margin-bottom:5px;
    }
    span {
      display: inline-block;
      vertical-align: middle;
      line-height: normal;
    }
    
    <div>
      <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> </div> <div> <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span> </div> <div> <span>Lorem ipsum dolor sit amet.</span> </div> <div>
  • 18

    垂直对齐中心的一个非常简单和最强大的解决方案:

    .outer-div {
      height: 200px;
      width: 200px;
      text-align: center;
      border: 1px solid #000;
    }
    
    .inner {
      position: relative;
      top: 50%;
      transform: translateY(-50%);
      color: red;
    }
    
    <div class="outer-div">
      <span class="inner">No data available</span>
    </div>
    
  • 0

    我不确定是否有人已经走了 writing-mode 路线,但我认为它干净利落地解决了这个问题并且有一个 broad support

    .vertical {
      //border: 1px solid green;
      writing-mode: vertical-lr;
      text-align: center;
      height: 100%;
      width: 100%;
    }
    .horizontal {
      //border: 1px solid blue;
      display: inline-block;
      writing-mode: horizontal-tb;
      width: 100%;
      text-align: center;
    }
    .content {
      text-align: left;
      display: inline-block;
      border: 1px solid #e0e0e0;
      padding: .5em 1em;
      border-radius: 1em;
    }
    
    <div class="vertical">
      <div class="horizontal">
        <div class="content">
          I'm centered in the vertical and horizontal thing
        </div>
      </div>
    </div>
    

    当然,这将适用于您需要的任何尺寸(除了父母的100%) . 如果取消注释边框线,熟悉自己会很有帮助 .

    JSFiddle demo让你小提琴 .

    Caniuse support:85.22%6.26%= 91.48% (甚至IE也在!)

  • 3

    您可以使用以下代码段作为参考 . 它对我来说就像一个魅力:

    <!DOCTYPE html>
        <html lang="de">
            <head>
                <title>Vertically Center Text</title>
                <style>
                    html, body {
                        height: 100%;
                        margin: 0;
                        padding: 0;
                        width: 100%;
                    }
                    body {
                        display: table;
                    }
                    .centered-text {
                        text-align: center;
                        display: table-cell;
                        vertical-align: middle;
                    }
                </style>
            </head>
    
            <body style="background:#3cedd5">
                <div class="centered-text">
                    <h1>Yes, it's my landing page</h1>
                    <h2>Under construction, coming soon!!!</h2>
                </div>
            </body>
        </html>
    

    上面代码段的输出如下:

    源代码信用:How do I vertically center text with CSS? - Code Puran

  • 0

    对此更好的想法 . 你也可以这样做

    body,
    html {
      height: 100%;
    }
    
    .parent {
      white-space: nowrap;
      height: 100%;
      text-align: center;
    }
    
    .parent:after {
      display: inline-block;
      vertical-align: middle;
      height: 100%;
      content: '';
    }
    
    .centered {
      display: inline-block;
      vertical-align: middle;
      white-space: normal;
    }
    
    <div class="parent">
      <div class="centered">
        <p>Lorem ipsum dolor sit amet.</p>
      </div>
    </div>
    
  • 15

    供参考,并添加一个更简单的答案:

    纯CSS:

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

    或者作为SASS / SCSS Mixin:

    @mixin vertical-align {
        position: relative;
        top: 50%;
        -webkit-transform: translateY(-50%);
        -ms-transform: translateY(-50%);
        transform: translateY(-50%);
    }
    

    使用者:

    .class-to-center {
        @include vertical-align;
    }
    

    作者:SebastianEkström的博客文章Vertical align anything with just 3 lines of CSS

    由于元素被放置在“半像素”上,该方法可能导致元素模糊 . 对此的解决方案是将其父元素设置为preserve-3d . 喜欢以下:

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

    我们住在2015年,每个主要的现代浏览器都支持Flex Box .

    它将是从现在开始制作网站的方式 .

    Learn it!

  • 35

    尝试转换属性:

    #box {
      height: 90px;
      width: 270px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    
    <div Id="box">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </div>
    
  • 3

    我需要一排可点击的大象,垂直居中,但没有使用表来解决一些Internet Explorer 9的怪异问题 .

    我最终找到了最好的CSS(根据我的需要),它很适合Firefox,Chrome和Internet Explorer 11.可悲的是Internet Explorer 9还在嘲笑我......

    div {
      border: 1px dotted blue;
      display: inline;
      line-height: 100px;
      height: 100px;
    }
    
    span {
      border: 1px solid red;
      display: inline-block;
      line-height: normal;
      vertical-align: middle;
    }
    
    .out {
      border: 3px solid silver;
      display: inline-block;
    }
    
    <div class="out" onclick="alert(1)">
      <div> <span><img src="http://www.birdfolk.co.uk/littleredsolo.png"/></span> </div>
      <div> <span>A lovely clickable option.</span> </div>
    </div>
    
    <div class="out" onclick="alert(2)">
      <div> <span><img src="http://www.birdfolk.co.uk/bang2/Ship01.png"/></span> </div>
      <div> <span>Something charming to click on.</span> </div>
    </div>
    

    显然你不需要边框,但它们可以帮助你看看它是如何工作的 .

  • 5

    对于单行文本(或单个字符),您可以使用此技术:

    #box 具有非固定的 relative height in % 时,可以使用 can .

    <div id="box"></div>

    #box::before {
        display: block;
        content: "";
        height: 50%;
    }
    
    #box::after {
        vertical-align: top;
        line-height: 0;
        content: "TextContent";
    }
    

    查看JsBin的现场演示(更容易编辑CSS)或JsFiddle(更容易更改结果框架的高度) .

    如果要将内部文本放在HTML中而不是CSS中,则需要将文本内容包装在附加的内联元素中,然后编辑 #box::after 以匹配它 . (当然,应删除 content: 属性 . )
    例如,
    <div id="box"><span>TextContent</span></div>
    在这种情况下, #box::after 应该替换为 #box span .

    对于IE8支持,您必须将 :: 替换为 : .

  • 104

    我想延长@michielvoo的答案,以释放行高和呼吸div高度的需要 . 它基本上只是这样的简化版本:

    div {
      width: 250px;
      /* height: 100px;
      line-height: 100px; */
      text-align: center;
      border: 1px solid #123456;
      background-color: #bbbbff;
      padding: 10px;
      margin: 10px;
    }
    
    span {
      display: inline-block;
      vertical-align: middle;
      line-height: normal;
    }
    
    <div>
      <span>All grown-ups were once children... but only few of them remember it</span>
    </div>
    
    <div>
      <span>And now here is my secret, a very simple secret: It is only with the heart that one can see rightly; what is essential is invisible to the eye.</span>
    </div>
    

    注意:封闭 divfixed-height 需要注释 css 的一部分 .

  • 55

    请尝试以下代码:

    display: table-cell;
    vertical-align: middle;
    
    div {
      height: 80%;
      width: 100%;
      text-align: center;
      display: table-cell;
      vertical-align: middle;
      background: #4CAF50;
      color: #fff;
      font-size: 50px;
      font-style: italic;
    }
    
    <div>
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
    </div>
    
  • 13

    如果您不关心它的小视觉3D效果,请将其设置在 button 而不是 div .

    #box
    {
      height: 120px;
      width: 300px;
      background: #000;
      font-size: 48px;
      font-style: oblique;
      color: #FFF;
    }
    
    <button Id="box" disabled>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </button>
    
  • 9

    我看到了之前的答案,它们只适用于那个宽度的屏幕(没有响应) . 对于响应,您必须使用flex .

    例:

    div{ display:flex; align-item:center;}
    
  • 3
    .box {  
      width: 100%;
      background: #000;
      font-size: 48px;
      color: #FFF;
      text-align: center;
    }
    
    .height {
      line-height: 170px;
      height: 170px;
    }
    
    .transform { 
      height: 170px;
      position: relative;
    }
    
    .transform p {
      margin: 0;
      position: absolute;
      top: 50%;
      left: 50%;
      -ms-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
    }
    
    <h4>Using Height</h4>
    <div class="box height">
      Lorem ipsum dolor sit
    </div>
    
    <hr />
    
    <h4>Using Transform</h4>
    <div class="box transform">
      <p>Lorem ipsum dolor sit</p>
    </div>
    
  • 3

    For all your vertical alignment needs!

    声明这个Mixin:

    @mixin vertical-align($position: relative) {
      position: $position;
      top: 50%;
      -webkit-transform: translateY(-50%);
      -ms-transform: translateY(-50%);
      transform: translateY(-50%);
    }
    

    然后将其包含在您的元素中:

    .element{
        @include vertical-align();
    }
    
  • 3

    您可以通过添加以下CSS代码轻松完成此操作:

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

    这意味着你的CSS最终看起来像:

    #box {
      height: 90px;
      width: 270px;
      background: #000;
      font-size: 48px;
      font-style: oblique;
      color: #FFF;
      text-align: center;
      margin-top: 20px;
      margin-left: 5px;
      display: table-cell;
      vertical-align: middle;
    }
    
    <div id="box">
      Some text
    </div>
    
  • 1

    作为答案接受的解决方案是完美的使用 line-height 与div的高度相同,但是这个解决方案在文本被包装时不能完美地工作或者是两行 .

    如果文本被包装或在div内的多行上尝试这个 .

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

    有关更多参考,请参阅:

  • 0

    所有信用都归于此链接所有者@SebastianEkströmLink;请仔细阅读 . 在行动中看到它codepen . 通过阅读上面的文章,我也创建了a demo fiddle .

    只需三行CSS(不包括供应商前缀),我们就可以在变换的帮助下完成:即使我们不知道它的高度,translateY也可以垂直居中 .

    CSS属性变换通常用于旋转和缩放元素,但是使用translateY函数,我们现在可以垂直对齐元素 . 通常这必须通过绝对定位或设置线高来完成,但这些要求您要么知道元素的高度,要么仅适用于单行文本等 .

    所以,为此,我们写道:

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

    这就是你所需要的一切 . 这是一种与绝对位置方法类似的技术,但我们不需要在父元素上设置任何高度或者在父元素上设置position-property . 它开箱即用,即使在Internet Explorer 9

    为了使它更简单,我们可以将其作为mixin与其供应商前缀一起编写 .

  • 0

    无论屏幕大小或 div 大小,以下代码都会将div放在屏幕中间:

    .center-screen {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      text-align: center;
      min-height: 100vh;
    }
    
    <html>
     <head>
     </head>
     <body>
     <div class="center-screen">
     I'm in the center
     </div>
     </body>
     </html>
    

    查看有关 flex here的更多详细信息 .

  • 1033

    简单而通用的方式是(作为michielvoo表方法):

    [ctrv]{
        display:table !important;
    }
    
    [ctrv] > *{ /* adressing direct discendents */
          display:table-cell;
          vertical-align: middle;
          // text-align: center; /* optional */
    }
    

    在父标记上使用此属性(或等效类)甚至可以使许多子对齐:

    <parent ctrv>  <ch1/>  <ch2/>   </parent>
    
  • 0

    您可以尝试这种基本方法:

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

    它只适用于单行文本,因为我们将行的高度设置为与包含框元素相同的高度 .


    一种更通用的方法

    这是垂直对齐文本的另一种方法 . 此解决方案适用于单行和多行文本,但仍需要固定高度的容器:

    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>
    

    CSS只调整 <div> 的大小,垂直居中通过设置 <div> 的行高等于其高度来对齐 <span> ,并使 <span> 成为 vertical-align: middle 的内联块 . 然后它将 <span> 的行高设置回正常,因此其内容将在块内自然流动 .


    模拟表格显示

    这是另一个选项,可能不适用于较旧的browsers that don't support display: table and display: table-cell(基本上只是Internet Explorer 7) . 使用CSS我们模拟表行为(因为表支持垂直对齐),HTML与第二个示例相同:

    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>
    

    使用绝对定位

    这种技术使用绝对定位的元素设置顶部,底部,左侧和右侧为0.在Smashing Magazine,Absolute Horizontal And Vertical Centering In CSS的文章中有更详细的描述 .

  • 3

    较新的浏览器现在支持CSS calc 功能 . 如果您要定位这些浏览器,则可能需要考虑执行以下操作:

    <div style="position: relative; width: 400px; height: 400px; background-color: red">
      <span style="position: absolute; line-height: 40px; height: 80px; text-align: center; width: 300px; overflow: hidden; top: calc(50% - 40px); left: calc(50% - 150px);">
        Here are two lines that will be centered even if the parent div changes size.
      </span>
    </div>
    

    关键是在绝对或相对定位的父div中使用 style = "top: calc(50% - [innerFixedHeightInPX/2]px); height: [innerFixedHeightInPX]px;" .

相关问题