在使用填充时,是否可以使文本始终完美居中?

时间:2017-11-28 16:29:48

标签: html css centering

我有一个像这样的简单布局:

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

应用此样式表:

.centered {
text-align: center;
}

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

我正在寻找一种在.msg课程中应用填充的方法,同时仍然保持.msg文本完全居中于正文。

正如您在此fiddle中看到的那样:

使用padding 0,文字始终完全居中。

padding-0

如果我使用padding200px,那么定心就不再完美了。

padding-200

在使用填充时,我该怎样做才能保持完美的居中?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

使用位置和变换的组合:

* {
  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>

添加背景以显示它完全居中。它也适用于任何数量的文本:

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>

添加了一个显示的计时器。