center div on top of img without using position

Advertisements

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 class="imgCon">
  <!--center this-->
  <div class="iconCon">
    C
  </div>
  <img src="https://www.vitalground.org/wp-content/uploads/2021/11/Bart-the-Bear-II--e1637176991443.jpg" />
</div>

>Solution :

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 class="imgCon">
  <img src="https://www.vitalground.org/wp-content/uploads/2021/11/Bart-the-Bear-II--e1637176991443.jpg" />
  <!--center this-->
  <div class="iconCon">
    C
  </div>
</div>

Leave a ReplyCancel reply