Как отцентрировать текст по вертикали, который имеет положение: абсолютное? - PullRequest
0 голосов
/ 19 марта 2019

Я бы хотел создать эффект скрытия при наведении. Моя цель здесь: 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 Ответ

1 голос
/ 19 марта 2019

Для вертикального центрирования абсолютного элемента внутри относительного родительского элемента вы можете использовать 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...