I have a page where I’d like a thumbnail to pop up when hovering over a link, and the full image open in a new page when the link is clicked. The following code does this, but the popup image can appear out of the viewport. Is there a way using css to assure that the full thumbnail image is in the viewport?
html:
<span class="popup-wrap">
<a class="popup" href="images/flamingo.jpg">flamingo
<span>
<img src="images/flamingo.jpg" alt="flamingo" />
</span>
</a>
<a class="popup" href="images/enough.jpg">enough
<span>
<img src="images/enough.jpg" alt="enough" />
</span>
</a>
</span>
css:
.popup-wrap { position:relative;}
.popup span {
position:absolute;
visibility:hidden;
}
.popup:hover, .popup:hover span {
visibility:visible;
z-index:1;
}
img {
max-width: 200px;
max-height: 200px;
}
2
Answers
I’m not sure what you want, but if the only problem you have is an overflow of the image, try this:
This will limit the image to the span, hiding any overflow, and make the size of the span 100% of .popup-wrap.
Try Out This
To ensure that the full thumbnail image is always within the viewport when the popup is triggered, you can add some CSS to calculate and adjust the position of the popup if it goes beyond the viewport boundaries. To achieve this, you can use a combination of calc, min, and max functions. Below is the modified CSS code:
Explanation:
I’ve moved the max-width and max-height styles from the img rule to the .popup span img rule. This ensures that the thumbnail image within the popup respects the maximum dimensions.
The popup:hover span rule now centers the popup horizontally using left: 50% and transform: translateX(-50%). The bottom property is used to position the popup just above the link (calc(100% + 10px) provides a small gap between the link and the popup).
I’ve added two media queries: one for screens larger than 767px width and one for screens smaller than or equal to 767px width. These media queries handle the popup’s position when it is about to go off-screen on the right and left sides, respectively. The calc(50% – 100px) value in both media queries is half of the thumbnail’s width (200px / 2 = 100px).
These changes should help ensure that the full thumbnail image stays within the viewport when the popup is triggered. Adjust the max-width and max-height values as needed to fit your design.