Search code examples
cssreactjsantd

Positioning a <Button> float: right over an <Image>


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.


Solution

  • 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>