Search code examples
htmlcssflexboxresponsive-designcss-selectors

How to create circular background behind a div?


I am trying to recreate this card using CSS.

enter image description here

However I can't figure out how to create the HTML and CSS. When I create a div and give it a background cololour and relative position, the Image is getting pushed out.

.Card {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 250px;
  height: 350px;
  background-color: white;
}

.CardHeader {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.CardHeader div {
  width: 150px;
  height: 150px;
  background-color: #ff9301;
  display: inline;
  position: relative;
  left: -15px;
}

.CardHeader img {
  width: 100px;
  height: 100px;
  background-color: red;
}
<div class="Card">
  <div class="CardHeader">
    <div></div>
    <Image src="/imgs/desktop-solid.svg" width={100} height={100} alt="Image" />
  </div>
  <div class="CardBody">
    <h2>Title</h2>
    <p>
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Lorem ipsum dolor sit amet consectetur adipisicing elit. Lorem ipsum dolor sit amet consectetur adipisicing elit. Lorem ipsum dolor sit amet consectetur adipisicing elit.
    </p>

  </div>
</div>


Solution

  • Few things to learn:

    Place the image inside the div element

    Use position:absolute on the image to allow you to move the image layer

    Use overflow:hidden; on the div to 'cut off' the the image so it doesn't appear outside the container.

    You also don't need the extra div element inside the card header - just use the card header as the parent.

    .Card {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 300px;
      height: 350px;
      background-color: lightgray;
      border-radius:10px;
    }
    
    .CardHeader {
      display: flex;
      flex-direction: column;
      width: 300px;
      height: 150px;
      background-color: #ff9301;
      display: inline;
      position: relative;
      overflow: hidden;
      border-radius: 10px 10px 0 0;
    }
    
    .CardHeader img {
      width: 150px;
      height: 150px;
      background-color: red;
      position: absolute;
      top: -20%;
      left: -10%;
      border-radius: 50%;
     }
    <div class="Card">
      <div class="CardHeader">
        <Image src="/imgs/desktop-solid.svg" width={100} height={100} alt="Image" />
    
    
      </div>
      <div class="CardBody">
        <h2>Title</h2>
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Lorem ipsum dolor sit amet consectetur adipisicing elit. Lorem ipsum dolor sit amet consectetur adipisicing elit. Lorem ipsum dolor sit amet consectetur adipisicing elit.
        </p>
    
      </div>
    </div>