Search code examples
htmlcsscentering

Is it possible to have a text always perfectly centered while using padding on it?


I have a simple layout like this :

<div class="centered">
<p class="msg">This is an important message</p>
</div>

with this style sheet applied on it :

.centered {
text-align: center;
}

.msg {
border: 1px solid red;
color: red;
display: inline-block;
padding: 200px;
}

I'm looking for a way to apply a padding on the .msg class while still keeping the .msg text perfectly centered in the body.

As you can see in this fiddle :

With a padding of 0, the text is always perfectly centered.

padding-0

If I use a padding of i.e 200px, the centering isn't perfect anymore.

padding-200

What should I do to keep perfect centering while using padding ?

Thank you for any help.


Solution

  • Use a combination of position and transform this way:

    * {
      margin: 0;
      padding: 0;
      line-height: 1;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      box-sizing: border-box;
    }
    html, body, .centered {
      height: 100%;
    }
    .centered {
      position: relative;
    }
    .msg {
      position: absolute;
      text-align: center;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: #f90;
    }
    <div class="centered">
      <p class="msg">This is an important message</p>
    </div>

    Added background to show it's perfectly centered. It also works with any amount of text:

    window.onload = function () {
      setTimeout(function () {
        message.innerHTML = "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, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
      }, 1000);
    };
    * {
      margin: 0;
      padding: 0;
      line-height: 1;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      box-sizing: border-box;
    }
    html, body, .centered {
      height: 100%;
    }
    .centered {
      position: relative;
    }
    .msg {
      position: absolute;
      text-align: center;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: #f90;
    }
    <div class="centered">
      <p class="msg" id="message">This is an important message</p>
    </div>

    Added a timer to show.