Place an <a> hyperlink on top of an <img> element with adaptive responsiveness

I'm working on a React application and I want to overlay multiple links using <a> tags on top of an image <img>. Initially, this seemed easy but I ran into an issue - when the window is resized (on different devices, for example), the positioning of the links and the image scale differently.

To demonstrate this problem, I've created a JSFiddle. If you resize the window in the bottom right corner, you'll notice that the link doesn't stay "glued" to the image. How can I solve this?

Here's the functional component code from the fiddle:

<div class="parentDiv">

    <div className={styles.imgWrapper}>
        <img 
            className={styles.imgResponsive} 
            src="https://cdn.pixabay.com/photo/2018/02/08/22/27/flower-3140492__480.jpg" 
        />
        <div class="divLink">
            <a href="some_url">Some link</a>
        </div>
    </div>
</div>

And here is the CSS being used:

.parentDiv {
    height: 70vh;
    width: 100vw;
}

.imgResponsive {
    position:relative;
    height: 100%;
    width:auto;
    top: 0;
    left: 0;
}

.divLink {
    position: absolute;
    top: 20%;
    left: 20%;
}

Any suggestions on how I can make the link stay attached to the image even after window resizing would be greatly appreciated! Thank you!

Answer №1

To ensure an image is displayed properly on a webpage, it is important to set its size in the CSS rule either using pixels or percentage values. Without specifying a size, the image will appear in its original size and may not be responsive.

Simply setting the width property should be enough, but for added certainty, you can include height: auto as well. Alternatively, defining the height property and including width: auto can achieve the same result.

When dealing with text links, centering them using

left: 50%; top: 50%; transform: translate(-50%, -50%);
is recommended for better responsiveness. It may also be beneficial to specify a smaller font-size within a media query.

A couple of additions to consider after reviewing the provided fiddle:

1.) There is a div layer called .imgWrapper between the parent element and the image itself. To ensure this wrapper matches the size of the parent element, add the following CSS:

.imgWrapper {
  height: 100%;
  width: 100%;
}

This allows the image's height: 100% setting to be relative to the 70vh height of .parentDiv.

2.) Since there is no ReactJS in the fiddle provided, make sure to specify classes in the HTML code as regular attributes, like so:

<img class="imgResponsive" src="https://cdn.pixabay.com/photo/2018/02/08/22/27/flower-3140492__480.jpg" />

See the result here: https://jsfiddle.net/9fqohL2m/1/

Answer №2

Minor adjustment needed due to the default browser style causing margin issues:

* {
    margin:0;
    padding:0;
    margin-block-start:0;
    margin-block-end:0;
}
.containerDiv {
    height: 80vh;
    width: 120vw;
}

.responsiveImg {
    position:relative;
    width:100%;
    top: 0;
    left: 0;
}

.linkDiv {
    position: absolute;
    top: 10vw;
    left: 10vw;
}

The * {} rule applies the styling universally with lower priority.
If you are still experiencing issues, refer to the code snippet I used for adding markers to a map here
Hopefully, this adjustment resolves the issue.

Answer №3

To ensure the image resizes properly with the page, you can either adjust it using percentages or pixels:

.parentDiv {
    height: 70vh;
    width: 100vw;
}

.imgResponsive {
    position:relative;
    width:100%;
    top: 0;
    left: 0;
}

.divLink {
    position: absolute;
    top: 20%;
    left: 20%;
}

If you prefer a fixed-width image (although this may cause issues on different devices), you can set it up like this:

.parentDiv {
    height: 70vh;
    width: 100vw;
}

.imgResponsive {
    position:relative;
    top: 0;
    left: 0;
}

.divLink {
    position: absolute;
    top: 96px;
    left: 96px; /*adjust as needed*/
}

I hope these solutions prove helpful for your needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assign a specific style to Fancybox links and buttons for managing the functions of 'next', 'previous', and 'close'

Utilizing the following jQuery script to hide a div whenever anything that does not have the class 'click' is clicked (used for empty space and certain other divs). $(document).click(function (event) { if (!$(event.target).hasClass('cli ...

Creating an HTML table that adjusts to the screen height with square-shaped cells

var grid = document.getElementById("grid"); var size = 50; for (var y = 0; y < size; y++) { var currentRow = grid.insertRow(0); for (var x = 0; x < size; x++) { var currentCell = currentRow.insertCell(-1); currentCell.style.height = currentCell.styl ...

Issues arising from the arrangement of the menu bar

I created a navigation bar using an unordered list (ul) with list items (li). However, I encountered an issue where the items were displaying in reverse order until I applied the following CSS: .nav-bar .btn{ float: left; } .nav-bar u ...

Interactive Sidebar Navigation Content

On my website, I have a navigation sidebar that contains links to all of the main site pages. Each page has the same links, except the link to the current page is not included, making it easy to visually identify which page you are on. Currently, I manuall ...

Tips for adjusting the scrollbar in Tailwind (next.js/react)

Having trouble changing the appearance of my scrollbar in a single page application using Tailwind (react/next). I've attempted to create custom CSS for the first div in my index file, like so: <div className="no-scroll"> <<< ...

When you apply margins in CSS and HTML, it can cause elements to break out of the row alignment

I'm struggling with my html code that contains elements arranged in rows: <div class = "row"> <div class="col-sm-3 cont-box"> <h1>Title1<h1> </div> <div class="col-sm9 cont-box"> <img src="onepic.jpeg" class=" ...

How can you customize the appearance of the filledInput component within a TextField component in Material UI?

I need some guidance on how to change the color of the FilledInput component within a TextField. Unlike InputProps, FilledInputProps are not directly accessible for styling with classes. Any suggestions on how I can customize the styling of the FilledInpu ...

What causes an absolutely positioned element to be positioned by its sibling rather than at the top corner of the page?

Can someone explain to me why my absolutely positioned element is displaying after my child_static div? I'm under the impression that absolutely positioned elements are removed from the normal flow. So why isn't child_absolute covering the child_ ...

Is it possible to capture the child element's id?

After loading several images onto the page, I hide them using 'display:none': <div id="cont-img"> <img class="lista-img" src="list/1.png" id="v1" /> <img class="lista-img" src="list/2.png" id="v2" /> <img class=" ...

Assign the Click event of the Button to the Recat Link, triggering a function when the button is clicked, followed by navigation to another component

I am trying to configure a Link to navigate to another component and also call a function when the same button is clicked. addValue(evt) { evt.preventDefault(); if(this.state.value !=undefined) { alert('Your input value ...

Issues with inline display not being rendered properly in HTML/CSS

I've been attempting to place an image and an h1 element on the same line. After researching online, I attempted using display:inline; for both the parent div element as well as each individual element. This is my current code: <div style="displa ...

The PHP script is exhausting memory resources and triggering a fatal error

I encountered the following error message: Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 528384 bytes) in /home/u234536193/domains/monetizingonline.com/public_html/wp-includes/wp-db.php on line 2024 The problematic cod ...

Add stylish stripes to your tables with ng-repeat

I need to display a large set of data in a table using ng-repeat. Each row has only one <tr> element. I want to alternate the color of rows, with odd rows in one color and even rows in another. However, I'm struggling to achieve this using ng-re ...

Image hover effect displayed when hovering over an image

Is it possible to create a hover effect using purely CSS when hovering over an image, like in this example: https://i.sstatic.net/jjAWm.jpg I've come across several similar examples online, but they all seem to rely on jquery or javascript. I'm ...

Tips for resolving issues with the header and scrolling content

I am new to CSS and I understand that it is quite simple: Question: I have a sample HTML page below, and when I scroll the page, the header does not stay fixed in one place. What am I missing here? Please assist. window.onscroll = function() { myFunc ...

Leveraging the sibling combinator for altering the class of a sibling SVG element with the assistance of Material

I have created an SVG picture that I am trying to animate. Behind the elements I want to animate on mouse hover, I have added transparent rectangles. The hover effect works well on these elements as the cursor changes to pointer. However, when I attempt t ...

Set up the Storybook Docs addon to showcase theme.dark

I've been struggling to set up a dark theme for Storybook, and so far I haven't found a solution to this issue. Following the Storybook documentation, I have configured the manager.js file as follows: // .storybook/manager.js import { addons } ...

Using HTML and CSS to create a flexbox layout with multiple rows

.ent__food__image { display: flex; justify-content: end; } .bev__food__image { display: flex; justify-content: end; } .kids__food__image { display: flex; justify-content: end; } <main class="flex-container"> <!-- Entrees --> & ...

What could be causing my React Swiper elements to slide when I click a button?

After reusing the swiper code from promotion-slider.js in the FlashDealsProducts.js file with some modifications, I noticed that both components were sliding in the same direction when either of the slide buttons was clicked. Despite attempting to change t ...

What is a way to increase the boldness of an HTML anchor tag when hovering without using CSS, but by modifying the inline style?

Is it possible to make the following anchor tags appear bolder on hover using inline styles, without utilizing any external or embedded CSS file? <a href="https://en.wikipedia.org/wiki/Internet_of_Things" target="_blank">Internet of things<br& ...