基于不工作的流动边距将文本居中到页面
Center a text to the page based on fluid margin not working
我一直在尝试将文本设置到屏幕中央。所以我直接在正文中放置了一个 div 和一些文本,并添加了一些文本,并将高度添加为 50%,将 margin-top 添加为 50%。我认为它将 div 的最高位置始终保持在 50%。但是我错了
HTML:
<div id="test">test.. !</div>
CSS:
html, body {
width:100%;
height:100%;
margin:0;
}
div {
margin-top:50%;
text-align:center;
width:100%;
height:50%;
}
您对它为什么会出现异常有任何想法吗?请不要提出任何新想法。我知道将其居中的其他想法。但我想知道为什么这段代码不起作用。
DEMO
这主要是一个“50% 与什么有关?”的问题
将 div
的高度设置为 50%
使其高度为其容器的 50%,在本例中为 body
元素。
将 margin-top
设置为 50%
然后将上边距设为 div
.
的 宽度 的一半
请在 SO 上查看此问题以进行说明:Why are margin/padding percentages in CSS always calculated against width?
此外,上边距应用在父级和 div
的 顶边 之间,而不是垂直中心。
所有这些因素都会导致 div
未在其容器中居中。
试试这个
html, body {
width:100%;
height:100%;
margin:0;
}
div {
width:100%;
height:50%;
overflow: auto;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
text-align:center;
border:1px solid black;
}
我一直在尝试将文本设置到屏幕中央。所以我直接在正文中放置了一个 div 和一些文本,并添加了一些文本,并将高度添加为 50%,将 margin-top 添加为 50%。我认为它将 div 的最高位置始终保持在 50%。但是我错了
HTML:
<div id="test">test.. !</div>
CSS:
html, body {
width:100%;
height:100%;
margin:0;
}
div {
margin-top:50%;
text-align:center;
width:100%;
height:50%;
}
您对它为什么会出现异常有任何想法吗?请不要提出任何新想法。我知道将其居中的其他想法。但我想知道为什么这段代码不起作用。
DEMO
这主要是一个“50% 与什么有关?”的问题
将 div
的高度设置为 50%
使其高度为其容器的 50%,在本例中为 body
元素。
将 margin-top
设置为 50%
然后将上边距设为 div
.
请在 SO 上查看此问题以进行说明:Why are margin/padding percentages in CSS always calculated against width?
此外,上边距应用在父级和 div
的 顶边 之间,而不是垂直中心。
所有这些因素都会导致 div
未在其容器中居中。
试试这个
html, body {
width:100%;
height:100%;
margin:0;
}
div {
width:100%;
height:50%;
overflow: auto;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
text-align:center;
border:1px solid black;
}