我有一个像这样的简单布局:
<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
即200px
,那么定心就不再完美了。
在使用填充时,我该怎样做才能保持完美的居中?
感谢您的帮助。
答案 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>
添加了一个显示的计时器。