Reputation: 3
I'd like to create a hover hide effect. My goal is here: 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>
I want to make the text that says "hover to show" to be centered vertically, how can I do this?
Upvotes: 0
Views: 38
Reputation: 17697
To center vertically an absolute element inside the relative positioned parent, you can use top:50%
( 50% means 1/2 parent height ) together with transform: translateY(-50%)
( 50% means 1/2 of element height ) .
This way it will be centered vertically even if parent and/or this element changes height
I added one line of css to hide the ' green ' div when user hovers over the ' spoiler '
* {
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>
Upvotes: 1