To position IconButton
relative to MainButton
, you must ensure that it is nested within MainButton
.
<MainButton type="button">
<img
src="https://4.img-dpreview.com/files/p/E~TS590x0~articles/3925134721/0266554465.jpeg"
alt="test"
/>
<IconButton>+</IconButton>
</MainButton>
Then adjust the positioning of IconButton
.
const IconButton = styled.span` // <-- using span for nesting button is not valid
background-color: #fff;
border-radius: 50%;
border: 2px solid red;
cursor: pointer;
position: absolute;
display: block;
width: 22px;
height: 22px;
line-height: 22px; // <-- vertically center text
position: relative;
margin-bottom: 0.5rem;
overflow: hidden;
left: 50%; // <-- position at parent's center
bottom: 0; // <-- align with parent's bottom
transform: translate(-50%, -50%); // <-- center the button
& > img {
width: 100%;
height: 100%;
object-fit: contain;
}
`;
Remove the overflow: hidden;
rule from the parent MainButton
.
https://i.sstatic.net/DCCEF.png
https://codesandbox.io/s/buttons-changing-forked-n4bw3?fontsize=14&hidenavigation=1&module=%2Fsrc%2FTable%2Findex.js&theme=dark
Update
Moved the image to be a background image and adjusted the positioning.
const MainButton = styled.button`
border-radius: 50%;
border: 2px solid red;
position: relative;
background-color: #fff;
background-image: ${({ src }) => `url(${src});`}
background-position: center center;
background-size: contain;
display: block;
width: 40px;
height: 40px;
position: relative;
margin-bottom: 0.5rem;
cursor: pointer;
& > img {
width: 100%;
height: 100%;
object-fit: contain;
}
`;
const IconButton = styled.div`
background-color: #fff;
border-radius: 50%;
border: 2px solid red;
cursor: pointer;
position: absolute;
display: block;
width: 22px;
height: 22px;
line-height: 22px;
position: relative;
margin-bottom: 0.5rem;
overflow: hidden;
text-align: center;
user-select: none;
left: 50%;
top: 100%;
transform: translate(-50%, -50%);
& > img {
width: 100%;
height: 100%;
object-fit: contain;
}
`;
https://i.sstatic.net/k9zNG.png
https://codesandbox.io/s/overlap-button-on-buttons-using-styled-components-forked-swo6t?fontsize=14&hidenavigation=1&module=%2Fsrc%2FTable%2Findex.js&theme=dark