'React.js - Styled components - center image in direct div parent with other objects
I understand that question looks pretty easy, but I haven't found anything helping me.
I have an image inside a div, and I want that image to be centered in that div even if I add, for example, a text.
Here is some code and images to better understand that problem :
If I only have my image in my div (with solid border), all is well :
<div>
<img height = '75px' width = '75px' src={USDCoin}/>
</div>
But adding a text, I can't figure out how to keep the image in the center of the div (well aligned with the grey lines) and the text below that :
<div>
<img height = '75px' width = '75px' src={USDCoin}/>
test
</div>
Here is a full example :
<div style = {{display: flex;
flex-direction: row;
height: 90%;
width: 100%;
justify-content: center;
align-items: center;}}>
<Line/>
<div>
<img height = '75px' width = '75px' src={USDCoin}/>
</div>
<Line/>
<Line/>
<div>
<img height = '75px' width = '75px' src={USDCoin}/>
test
</div>
<Line/>
</div>
Thank you in advance for your precious help !
Solution 1:[1]
You can use flexbox to do this very easily.
I've created an example here for you (doesn't include styled-components but your issue is not the styled components anyway) https://codesandbox.io/s/solitary-night-7859bz
Solution 2:[2]
you should use flex-direction: column;
import { React } from "react";
export default function Demo() {
return (
<>
<div
style={{
display: "flex",
flexDirection: "column",
height: "90%",
width: "100px",
border: "2px solid",
justifyContent: "center",
margin: "0 auto",
alignItems: "center"
}}
>
<div>
<img
height="75px"
width="75px"
src={
"https://images.unsplash.com/photo-1638913662252-70efce1e60a7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80"
}
/>
</div>
<div>test</div>
</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 | christiansany |
| Solution 2 | Sougata Mukherjee |


