'Position Absolute/Relative

i'm trying to create a button at the top right corner of an image. What happens is that the button goes to the top right corner, but of the entire page. I've tried putting the image and the button inside a div of their own,nothing happens.

This is the sass code :

.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1%;

  .card {
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .image {
      max-width: 400px;
      max-height: 400px;
      position: relative;
    }
    .like-btn {
      position: absolute;
      z-index: 1;
      border-radius: 5px;
      top: 0;
      right: 0;
    }
  }

  & > img {
    object-fit: cover;
  }
}

this is the JSX :

    <div className='card'>
      <div className='card-details'>
        <Link to={`/person/${people.id}`}>
          <h3>
            {people.name.title} {people.name.first} {people.name.last}
          </h3>
        </Link>
        <img alt='person' className='image' src={people.picture.large}></img>
        <button className='like-btn' onClick={() => setAddFavorite(people)}>
          Like
        </button>
        <p>{people.email}</p>
        <div>
          Location :{people.location.country}, {people.location.city},{people.location.street.name}
        </div>
        <span>ID : {people.id}</span>
      </div>
      {isModal ? <Modal people={people} setIsModal={setIsModal} /> : <div></div>}
    </div>

thanks in advance



Solution 1:[1]

An absolutely positioned element is positioned with respect to the edges of its nearest positioned ancestor.

The img element, which you have set position: relative on, is not an ancestor of the button element (and can't be, because img elements can't have children).

You need to wrap both elements in a contain (e.g. a div) and give that the dimensions you want along with relative positioning.

Solution 2:[2]

To set absolute position, you need a parent which has position:relative

.container{
  width: fit-content;
  position:relative;
  border:1px solid black;
}
img{
  width:300px;
}
button{
  position:absolute;
  top:20px;
  right:20px;
}
<div class="container">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Stack_Overflow_icon.svg/768px-Stack_Overflow_icon.svg.png" alt="">
  <button>Hi</button>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quentin
Solution 2 Cédric