CSS top属性,百分比值不起作用

时间:2015-08-10 03:55:00

标签: html css

CSS:

.header{
    position: absolute;
    top: 50%;
    left: calc(50% - 200px);
    opacity: 0.9;
    color: #ffffff;
    font-size: 35px;
    text-shadow: 2px 2px 5px #000000;
}

HTML:

<body>
<div class="background"></div>
<div style="position: relative">
    <div class="header"><label>A+ CMS</label></div>
</div>
</body>

输出:
enter image description here
left属性已正常运行,但top属性不适用。我将50%设置为top但是单词&#34; A + CMS&#34;一直挂在屏幕的顶部。
如果我将top的值从百分比更改为px,则可行。为什么呢?

2 个答案:

答案 0 :(得分:4)

那是因为它距离容器顶部10%,目前是文本的高度,所以它不会移动。

如果向容器添加height属性,则top属性将起作用。以下是此示例:http://jsfiddle.net/bncteqzv/

.header{
    position: absolute;
    top: 10%;
    left: calc(50% - 200px);
    opacity: 0.9;
    color: #ffffff;
    font-size: 35px;
    text-shadow: 2px 2px 5px #000000;
}

.test {
    height: 500px; 
}
<body>
<div class="background"></div>
<div class="test" style="position: relative">
    <div class="header"><label>A+ CMS</label></div>
</div>
</body>

答案 1 :(得分:0)

将高度赋予.container class div

&#13;
&#13;
.header{
    position: absolute;
    top: 50%;
    left: calc(50% - 200px);
    opacity: 0.9;
    color: #ffffff;
    font-size: 35px;
    text-shadow: 2px 2px 5px #000000;
}
.container {
    height: 500px; 
  background:red;
}
&#13;
<div class="background"></div>
<div class="container" style="position: relative">
    <div class="header"><label>A+ CMS</label></div>
</div>
&#13;
&#13;
&#13;