skip to Main Content

I’m using the following code to try and place a "Copy" button over the upper right hand corner of an image :

<div className="itemImg">
    <Button icon={<MdContentCopy />} style={{float: 'right'}} onClick={(e) => {copyItem(props.item.name)}} />
    <Image
        className="itemImg"
        src={"/api/feed/"+props.feed+"/"+props.item.name}
        preview={false}
    />
</div>

If the block is a , i.e. not an image, it works as expected, but for some reason, <Image> is having an issue, see below. The "Copy" icon should be placed atop the image because of float: right

enter image description here

Our good friend ChatGPT recommends not using float and rely on flex layout to do this. Not a big deal and it actually provided the solution, but I’d rather have minimal code and CSS over what antd/react provides natively.

2

Answers


  1. give the container a position: absolute and a width: min-content so it fits the image width.
    After that you can position the button with position: absolute

    .container {
      position: relative;
      width: min-content;
    }
    
    .container button {
      position: absolute;
      top: 0.5rem;
      right: 0.5rem;
    }
    <div class="container">
      <img src="https://via.placeholder.com/200.jpg">
      <button>Copy</button>
    </div>
    Login or Signup to reply.
  2. To solve that you need to create a container with position: relative and inside the container, you add your image and the button. but the button must have a position: absolute and add right and top values.
    I have added a snippet, you can change that to your react code using your components it will work the same.

    .image {
      height: 100%;
      width: 100%;
      object-fit: cover;
    }
    
    .container {
      position: relative;
      height: 300px;
      width: 300px;
    }
    
    .copy-btn {
      position: absolute;
      right: 10px;
      top: 10px;
    }
    <div class="container">
      <img alt="a goat" class="image" src="https://images.pexels.com/photos/17686105/pexels-photo-17686105/free-photo-of-animal-cute-agriculture-farm.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1">
      <button class="copy-btn">copy</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search