如何垂直居中放置具有绝对位置的文本?

时间:2019-03-19 15:58:21

标签: html5 css3

我想创建一个悬停隐藏效果。我的目标是:CodePen

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: #123456;
}

#object {
  background-color: cornsilk;
  border: #333 3px solid;
  margin: 20px auto;
  padding: 20px;
  position: relative;
  width: 750px
}

#spoiler {
  background-color: blue;
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  transition: 0.3s opacity linear;
  z-index: 5;
}

#spoiler:hover {
  opacity: 0;
}

#big {
  background-color: green;
  color: black;
  display: flex;
  justify-content: center;
  left: 0;
  position: absolute;
  right: 0;
  text-align: center;
/*   top: 0; */
  z-index: 20;
}
<div id="object">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae aperiam praesentium commodi optio ab saepe deserunt ullam et sequi doloremque consectetur hic laudantium inventore dignissimos, placeat modi nobis est nostrum.</p>
  <div id="spoiler"></div>
  <p id="big">Hover to show</p>
</div>

我想使显示“悬停显示”的文本垂直居中,该怎么做?

1 个答案:

答案 0 :(得分:1)

要在相对位置的父级中垂直放置绝对元素,可以将top:50%(50%表示1/2父级高度)与transform: translateY(-50%)(50%表示元素高度的1/2)一起使用)。

这样,即使父元素和/或此元素更改高度,它也将垂直居中

当用户将鼠标悬停在“剧透”上时,我添加了一行css来隐藏“绿色” div

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: #123456;
}

#object {
  background-color: cornsilk;
  border: #333 3px solid;
  margin: 20px auto;
  padding: 20px;
  position: relative;
  width: 750px
}

#spoiler {
  background-color: blue;
  bottom: 0;
  left: 0;
  position: absolute;
  right: 0;
  top: 0;
  transition: 0.3s opacity linear;
  z-index: 5;
}

#spoiler:hover {
  opacity: 0;
}

  

#big {
  background-color: green;
  color: black;
  display: flex;
  justify-content: center;
  left: 0;
  position: absolute;
  right: 0;
  text-align: center;
  top: 50%;
  transform: translateY(-50%);
  z-index: 20;
}

#spoiler:hover + #big {
  opacity:0;
}
<div id="object">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Beatae aperiam praesentium commodi optio ab saepe deserunt ullam et sequi doloremque consectetur hic laudantium inventore dignissimos, placeat modi nobis est nostrum.</p>
  <div id="spoiler"></div>
  <p id="big">Hover to show</p>
</div>