-1

I need to vertically align a text in center inside a div. I have found many of way, but none of them respects exact content of the text - I am talking about small graphical parts below text line - letter e.g. "ygq" etc., which is missing when e.g. capital letters are used "YGQ", but it's still counted when text is displayed. I tried:

.button {
    height: 20px;
    line-height: 20px;
}

<div class="button">My text</div> 
<div class="button">MY TEXT</div> 

and the other way

.button {
    height: 20px;
    display: flex;
    align-items: center;
}

<div class="button"><p>My text</p></div> 
<div class="button"><p>MY TEXT</p></div> 

I use padding attribute, when I am sure, no graphics below the line will be presented. Is there a way, how to align text generally based on its exact content?

Question How do I vertically center text with CSS? doesn't answer this as the solution is based on "line-height" which still takes count graphics below line as I mentioned in my question.

user3523426
  • 598
  • 1
  • 6
  • 19
  • 1
    Mentioned "duplicate" question doesn't solve the issue - line-height includes space for graphics below the line as I mention in my question. – user3523426 Mar 30 '19 at 10:22

3 Answers3

0

To make your elements vertical center, you can use display:flex with the parent container .button and apply margin:auto to child element.

 

.button{
    height: 150px;
    display: flex;
    background-color: aliceblue;
 }
.button p {
   margin: auto;
}
    <div class="button">
        <p>My text</p>
    </div>
Techie_T
  • 385
  • 2
  • 13
0

Try this::

.button{
  display: flex;
  justify-content: center; /* align horizontal */
  align-items: center; /* align vertical */
}
<div class="button">
        <p>My text</p>
    </div>
-1

You can use position and transform to align an item vertically inside an other

.button {
    position: relative;
}

.button p {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);

    /* For horizontal align */
    width: 100%;
    text-align: center;
}
    <div class="button">
        <p>My text</p>
    </div>