Go to Anchor tag in page with responsive images

Viewed 138

I have a page made with Bootstrap 4 that has responsive images and anchor tags in text.

.img-fluid {
    max-width: 100%;
    height: auto;
}

When I get to this page after clicking a link (like 'mypage#section-one') the page loads on the anchor tag (as usual), but when the images loads, the content of the page scrolls and I "lose" the anchor tag position. I know I could solve this by specifying image dimensions directly in the img tag like

<img src="cat.jpg" alt="A Cat" width="360" height="200">

But since the image is responsive, I have no way to know the height of the image. Is there a way to prevent this? By either get image height before loading or going to anchor after?

1 Answers

What you are describing is called Content Reflow. There are several ways to prevent this. Here it is a CSS Tricks article about it.

This shows a solution using "padding-top" with the height calculated using the aspect ratio of the image, and a solution using inline svg placeholders

Related