Image Rollover with CSS

The image rollover is done with CSS as follows. This example is a simplified version of the example at https://www.w3schools.com/howto/howto_css_image_overlay.asp. View the source code and notice the following:

  1. One div is nested inside of another div. The outer div is given a class of container and contains an image followed by a div.
  2. The inner div is given a class of overlay.
  3. The overlay class is given a position:absolute and a position of 0 (for top, bottom, left, right) and an opacity of 0.
    1. Absolute positioning positions the second image relative to the top left hand corner of the surrounding div. This overlays the second image on top of the first image (which is contained in the outer div).
    2. The opacity of 0 means the second image is fully transparent, and thus initially only the first image is visible
  4. The hover pseudo class is applied to the container and there is contextual CSS so that this alters the overlay class to have an opacity of 1 (other CSS properties of the overlay class are not affected). This makes the second image fully opaque and thus it appears, hiding the first image which is underneath because it is first in the html
  5. The width of the outside div is set equal to the width of the image. This ensures that when the cursor moves off the image, the hover effect will no longer be in place and thus the opacity of the overlay image will return to 0 (fully transparent). If the width of the outside div is not set, the div would extend all the way across the page and thus the "mouseout" effect would not occur if the mouse were to remain in this region that would extend the height of the image and the width of the page..
Bush
Romney

Revised: November 7, 2017