我在div中包含<div>
和<p>
,其中包含一些文字。
使用text-align:center
属性可以实现水平对齐,但我无法垂直对齐。
我检查了其他相关解决方案,但它们是针对该特定问题的,并不适合任何div大小。
我需要一个可能适用于任何不同尺寸div的解决方案(在我的情况下,宽度和高度都是100%)。
这是 Fiddle
答案 0 :(得分:7)
您可以top: calc(50% - 1em)
p
使用p {
position: relative;
top: calc(50% - 1em);
}
垂直居中。
height
我们的想法是获取文本的2
,将其除以calc(50% - ****)
,并在页面加载或调整窗口大小时在p
中使用它。然后找到top
标记的规则并修改var p = document.getElementsByTagName('p')[0];
function doMath() {
var ss = document.styleSheets;
for (k = 0; k < ss.length; k++) {
var rules = ss[k];
for (l = 0; l < rules.cssRules.length; l++) {
var r = rules.cssRules[l];
if (r.selectorText == "p") {
r.style.top = 'calc(50% - ' + String(parseInt(getComputedStyle(p).height.slice(0, -2)) / 2) + 'px)'
}
}
}
}
doMath();
window.onresize = doMath;
属性。
html,
body {
height: 100%;
width: 100%;
margin: 0 auto;
}
#dvTxt {
background-color: lightblue;
height: 100%;
width: 100%;
text-align: center;
vertical-align: middle;
}
p {
position: relative;
top: calc(50% - 7.5px);
}
<div id="dvTxt">
<p>This is my text. I want it to be centered vertically This is my text. I want it to be centered vertically This is my text. I want it to be centered vertically This is my text. I want it to be centered vertically This is my text. I want it to be centered
vertically This is my text. I want it to be centered vertically This is my text. I want it to be centered vertically This is my text. I want it to be centered vertically This is my text. I want it to be centered vertically This is my text. I want
it to be centered vertically This is my text. I want it to be centered vertically This is my text. I want it to be centered vertically This is my text. I want it to be centered vertically This is my text. I want it to be centered vertically This is
my text. I want it to be centered vertically This is my text. I want it to be centered vertically This is my text. I want it to be centered vertically</p>
</div>
{{1}}
答案 1 :(得分:2)
以下CSS将有效。
Text aligned center Vertically
CSS:
html,body{
height:100%;
width:100%;
}
#dvTxt{
background-color:lightblue;
height:100%;
width:100%;
text-align: center;
vertical-align: middle;
display: table;
}
#span {
display: table-cell;
vertical-align: middle;
line-height: normal;
}
HTML
<div id="dvTxt">
<p id="span">This is my text. I want it to be centered vertically</span>
</div>
答案 2 :(得分:1)
添加padding-top:50%到#dvTxt。对于不同的内容,它不是完美的解决方案,但您会明白下一步该做什么。对于现在的填充顶部:50%非常适合您的小提琴示例。
答案 3 :(得分:1)
您可以使用
position: absolute
请参阅DEMO
CSS:
html,body{
height:100%;
width:100%;
}
#dvTxt{
background-color:lightblue;
height:100%;
width:100%;
position: relative;
}
p {
width: 100%;
text-align: center;
position: absolute;
top: 50%;
}
答案 4 :(得分:1)
如果每个元素只有一行,那么更简单的解决方案就是使用行高。
#dvTxt{
background-color:lightblue;
height:100%;
width:100%;
text-align: center;
vertical-align: middle;
line-height:8em;
}
http://jsfiddle.net/o3smkvk9/10/
答案 5 :(得分:1)
您可以使用填充属性将文本垂直居中
#dvTxt{
background-color:lightblue;
height:100%;
width:100%;
text-align: center;
padding:50% 0;
}