skip to Main Content

I try to create simple message
And it’s works.
But the text is not verically centered even though I have it set vertical-align: middle;
Can you explain why?

.error-message {       
    animation: fadeOut 2s forwards;
    animation-delay: 1s;           
    color: #000000;
    font-size: 40px;
    padding: 40px;
    background: red;
    text-align: center;
    vertical-align: middle;
    position: absolute; left:0px; top:100px; width:100%;height:30px;
}

@keyframes fadeOut {
    from {opacity: 1;}
    to {opacity: 0;}
}
<h1>Hi friend, try edit me!</h1><br>
<h1>Hi friend, try edit me!</h1><br>
<h1>Hi friend, try edit me!</h1><br>
<h1>Hi friend, try edit me!</h1><br>
    
<div class="error-message">
  <p>Some message text</p>
</div> 

3

Answers


  1. Don’t use combinations of padding/margin/height/etc. for positioning of the contents of an element. Centering is trivial with Flexbox. For example:

    .error-message {       
        animation: fadeOut 2s forwards;
        animation-delay: 1s;           
        color: #000000;
        font-size: 40px;
        background: red;
        position: absolute;
        left:0px;
        top:100px;
        width:100%;
        height:110px;             /* add height to account for your previous padding */
        display: flex;            /* use CSS flex */
        justify-content: center;  /* horizontally center contents */
        align-items: center;      /* vertically center contents */
    }
    
    @keyframes fadeOut {
        from {opacity: 1;}
        to {opacity: 0;}
    }
    <h1>Hi friend, try edit me!</h1><br>
    <h1>Hi friend, try edit me!</h1><br>
    <h1>Hi friend, try edit me!</h1><br>
    <h1>Hi friend, try edit me!</h1><br>
        
    <div class="error-message">
      <p>Some message text</p>
    </div> 
    Login or Signup to reply.
  2. The ‘vertical-align’ property is primarily for aligning inline and inline-block elements with respect to their parnet div or element.

    Please refer this doc for verticle-align

    we can use Flexbox to center vertically in a block-level element.

    You just need to add below css properties inside .error-message class :

    display: flex;
    align-items: center;
    justify-content: center;
    
    Login or Signup to reply.
  3. you can just delete heigth: 30px to allow your messe-age decide which is the appropriate height to contain the inside paragraphe.

    /* height:30px; */
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search