如何垂直居中,有位置:绝对?

问题描述 投票:0回答:1

我想创建一个悬停隐藏效果。我的目标是: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>

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

html5 css3
1个回答
1
投票

要使相对定位父元素内的绝对元素垂直居中,可以使用top:50%(50%表示1/2父高度)和transform: translateY(-50%)(50%表示元素高度的1/2)。

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

当用户将鼠标悬停在'扰流板'上时,我添加了一行css来隐藏'green'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>
© www.soinside.com 2019 - 2024. All rights reserved.