前50%不适用于由填充底部设置高度的元素

时间:2017-10-02 06:32:38

标签: html css

我没有得到它,为什么我不能在%中使用top值?由.bg h1为元素定义了高度,因此听起来像设置高度的正式事物。是否有任何解决方法,但没有使它绝对,所以它会响应。



padding-bottom

html,
body {
  margin: 0;
  padding: 0;
}

.bg {
  background: #333;
  text-align: center;
  position: relative;
  height: auto;
  padding-bottom: 20%;
}

.bg h1 {
  color: #eee;
  margin: 0;
  padding: 0;
  position: relative; //change to absolute to ensure 
  //there is height value set without text inside
  top: 50%; //50px DOES work
}




3 个答案:

答案 0 :(得分:1)



html, body {
  margin:0;
  padding:0;
}
.bg {
  background:#333;
  //text-align:center;
  //position:relative;
  //height: auto;
  //padding-bottom: 20%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
}
.bg h1 {
  color:#eee;
  margin:0;
  padding:0;
  //position: absolute; //change to absolute to ensure 
                     //there is height value set without text inside
  //top:50%; //50px DOES work
}

<div class="bg">
  <h1>text</h1>
</div>
&#13;
&#13;
&#13;

我建议display: flex;

&#13;
&#13;
html, body {
  margin:0;
  padding:0;
}
.bg {
  background:#333;
  text-align:center;
  position:relative;
  //height: auto;
  //padding-bottom: 20%;
  height: 100px;
}
.bg h1 {
  color:#eee;
  //margin:0;
  padding:0;
  position: absolute; //change to absolute to ensure 
                     //there is height value set without text inside
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
&#13;
<div class="bg">
  <h1>text</h1>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

请检查一下。在.bg课程中根据需要提供高度。在课程.bg h1中,为top:50%; -webkit-transform: translateY(-50%); transform: translateY(-50%);提供居中文字。

html, body {
  margin:0;
  padding:0;
}
.bg {
  background:#333;
  text-align:center;
  position:relative;
  height: 100px; 
}
.bg h1 {
  color:#eee;
  margin:0;
  padding:0;
  position:relative; 
  top:50%; 
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
}
<div class="bg">
  <h1>text</h1>
</div>

答案 2 :(得分:0)

使用内联块和伪元素。因为.bghtml,body{ height:100%; } .bg{ background: #333; text-align: center; position: relative; height: auto; /* padding-bottom: 20%; */ /* height:100px; */ padding:10% 0; } .pseudo{ display: inline-block; width:1px; height:100%; vertical-align:middle; background:#cccccc; } .bg h1{ display: inline-block; vertical-align:middle; color: #eee; margin: 0; padding: 0; }匹配的背景太薄而且太明显了。

<div class="bg">
  <div class="pseudo"></div>
  <h1>text</h1>
</div>
email

相关问题