How do I vertically align text in a paragraph?

前端 未结 9 1626
余生分开走
余生分开走 2020-12-05 04:12

I would like to know to align the text in a p element to be vertically centered.

Here are my styles:

相关标签:
9条回答
  • 2020-12-05 04:27

    User vertical-align: middle; along with text-align: center property

    <!DOCTYPE html>
    <html>
    <head>
    <style>
    .center {
      border: 3px solid green;
      text-align: center;
    }
    
    .center p {
      display: inline-block;
      vertical-align: middle;
    }
    </style>
    </head>
    <body>
    
    <h2>Centering</h2>
    <p>In this example, we use the line-height property with a value that is equal to the height property to center the div element:</p>
    
    <div class="center">
      <p>I am vertically and horizontally centered.</p>
    </div>
    
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-05 04:34

    Below styles will vertically center it for you.

    p.event_desc {
     font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
     line-height: 14px;
     height: 35px;
     display: table-cell;
     vertical-align: middle;
     margin: 0px;
    }
    
    0 讨论(0)
  • 2020-12-05 04:36

    Try these styles:

    p.event_desc {
      font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
      line-height: 14px;
      height:75px;
      margin: 0px;
      display: table-cell;
      vertical-align: middle;
      padding: 10px;
      border: 1px solid #f00;
    }
    <p class="event_desc">lorem ipsum</p>

    0 讨论(0)
  • 2020-12-05 04:36

    You can use line-height for that. Just set it up to the exact height of your p tag.

    p.event_desc {
      line-height:35px;
    }
    
    0 讨论(0)
  • 2020-12-05 04:39

    you could use

        line-height:35px;
    

    You really shouldnt set a height on paragraph as its not good for accessibility (what happens if the user increase text size etc)

    Instead use a Div with a hight and the p inside it with the correct line-height:

        <div style="height:35px;"><p style="line-height:35px;">text</p></div>
    
    0 讨论(0)
  • 2020-12-05 04:44

    If the answers that involve tables or setting line-height don't work for you, you can experiment with wrapping the p element in a div and style its positioning relative to the height of the parent div.

    .parent-div{
      width: 100px;
      height: 100px;
      background-color: blue;
    }
    
    .text-div{
      position: relative;
      top: 50%;
      transform: translateY(-50%);
    }
    
    p.event_desc{
      font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
      color: white;
      text-align: center;
    }
    <div class="parent-div">
      <div class="text-div">
       <p class="event_desc">
        MY TEXT
       </p>
      </div>
    </div>

    0 讨论(0)
提交回复
热议问题