Revealing Hidden Elements By CSS Animations

Use-Cases of this Tutorial

  • You are looking for CSS animations to reveal hidden elements like images etc. Useful for showing coupon codes etc.
  • You are looking to show and hide elements through CSS animations

Example 1

Add a pseudo-element to the element which is to be revealed. On a click event, rotate the pseudo-element so that the inner element gets revealed.

The effect can be achieved by using a pseudo-element for the element which is to be hidden. There are a few points to note :

  • The element which is to be revealed must have a parent element. The overflow property of the parent must be set to hidden
  • The element must have position property as relative
  • The pseudo-element must have position property as absolute. This is because we want the pseudo-element to be 150% of the size (both height and width) of the hidden element. 150% is just an example — the main thing is that it should be greater than the hidden element, so that the pseudo-element completely sweeps by it.

HTML Markup :

<div id="parent">
	<div id="child"></div>
</div>
<button id="reveal-button">Reveal</button>

CSS :

#parent {
	overflow: hidden;
}

#child {
	position: relative;
	background-color: yellow;
}

/* Pseudo-element that hides the child */
#child::after {
	content: ''; 
	position: absolute;
	width: 150%;
	height: 150%;
	background-color: blue;
	top: 0;
	left: 0;
	bottom: 0;
	transform: rotate(0deg);
	transform-origin: 0px 0px;
	transition: transform linear 0.7s;
}

#child.animated::after {
	transform: rotate(90deg);
}

Javascript that toggles a CSS class to show and hide the element :

$("#reveal-button").on('click', function() {
	$("#child").toggleClass('animated');
});

Example 2

Add a pseudo-element to the element which is to be revealed. On a click event, scale down the pseudo-element to 0 so that the hidden element gets revealed.

The effect can be achieved by using a pseudo-element for the element which is to be hidden. There are a few points to note :

  • There is no need to have a parent element in this case.
  • The element must have position property as relative
  • The pseudo-element must have position property as absolute. This is because we want the pseudo-element to be of the same size as the hidden element.

HTML Markup :

<div id="child"></div>
<button id="reveal-button">Reveal</button>

CSS :

#child {
	background-color: yellow;
	border-radius: 50%;
	position: relative;
}

/* Pseudo-element that hides the child */
#child::after {
	content: '';
	position: absolute;
	width: 100%;
	height: 100%;
	background-color: blue;
	top: 0;
	left: 0;
	bottom: 0;
	transform: scale(1);
	transition: transform linear 0.5s;
	border-radius: 50%;
}

#child.animated::after {
	transform: scale(0);
}

Javascript that toggles a CSS class to show and hide the element :

$("#reveal-button").on('click', function() {
	$("#child").toggleClass('animated');
});