HTML Element Style How to - Create Basic CSS image swap on hover








Question

We would like to know how to create Basic CSS image swap on hover.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.foo img:last-child {<!--from ww  w  .j  a v a  2  s.c  om-->
  display: none
}

.foo:hover img:first-child {
  display: none
}

.foo:hover img:last-child {
  display: inline-block
}
</style>
</head>
<body>
<body>
  <a class="foo" href="#"> 
    <img src="http://lorempixel.com/400/200/food/1/" /> 
    <img src="http://lorempixel.com/400/200/food/2/" />
  </a>
</body>
</body>
</html>

The code above is rendered as follows: