I have a main container that contains an image and a div. What I want to achieve is to center the div on top of the image without having to use absolute or relative positioning on it. How can I achieve this? Thanks in advance.
.imgCon {
display: flex;
width: 95%;
height: 95%;
margin: auto;
background-color: blue;
}
.imgCon img {
width: 95.5%;
height: 95%;
margin: auto;
border-radius: inherit;
}
.iconCon {
display: flex;
justify-content: center;
align-items: center;
width: 30%;
height: 30%;
margin: auto;
color: #ffffff;
border-radius: 50%;
background-color: #000000;
}
<div >
<!--center this-->
<div >
C
</div>
<img src="https://www.vitalground.org/wp-content/uploads/2021/11/Bart-the-Bear-II--e1637176991443.jpg" />
</div>
CodePudding user response:
The only way I can think of without using absolute positioning or changing your markup is to use a CSS Grid and make both elements occupy the same cell.
.imgCon {
display: flex;
width: 95%;
height: 95%;
margin: auto;
background-color: blue;
display: grid;
}
.imgCon img {
width: 95.5%;
height: 95%;
margin: auto;
border-radius: inherit;
grid-column-start: 1;
grid-row-start: 1;
}
.iconCon {
display: flex;
justify-content: center;
align-items: center;
width: 4rem;
height: 4rem;
margin: auto;
color: #ffffff;
border-radius: 50%;
background-color: #000000;
grid-column-start: 1;
grid-row-start: 1;
}
<div >
<img src="https://www.vitalground.org/wp-content/uploads/2021/11/Bart-the-Bear-II--e1637176991443.jpg" />
<!--center this-->
<div >
C
</div>
</div>
CodePudding user response:
You could use background-image
property and tiny styling changes.
.imgCon {
display: flex;
justify-content: center;
align-items: center;
width: 20rem;
height: 20rem;
margin: auto;
background-color: blue;
background-image: url("https://www.vitalground.org/wp-content/uploads/2021/11/Bart-the-Bear-II--e1637176991443.jpg");
background-position: center center;
background-repeat: no-repeat;
background-size: 100% 80%;
}
.iconCon {
display: flex;
justify-content: center;
align-items: center;
width: 3rem;
height: 3rem;
margin: auto;
color: #ffffff;
border-radius: 50%;
background-color: #000000;
}
.container {
display: flex;
justify-content: center;
align-item: center;
}
<div >
<div >
<!--center this-->
<div >
C
</div>
</div>
</div>