简体   繁体   中英

CSS: How to make div adapt to image size?

I have implemented CSS status that allows to see if the user is online or not:
在此处输入图像描述
This is the CSS code:

.status-circle-online {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: rgb(255, 60, 0);
  border: 2px solid white;
  bottom: 10px;
  right: 10px;
  position: absolute;
}

This is the html code:

  <div>
    <img
      src={profileImageSrc}
      className="rounded-circle ml-3"
    />
    <div
      className={`status-circle-${online_or_offline_signal} cursor-pointer`}
    />
  </div>

The problem is that when I reduce window size, the status signal is no longer where it should be:
在此处输入图像描述

在此处输入图像描述

Any idea how to make it "stick" to the image?

Hard to say exactly without seeing more of your code. But you could try adding position: relative; to the containing div, and then for the red circle use percentages instead of pixels for right and bottom .

Position the parent div relative and then the absolute values of the status indicator will be relative to that container:

 .status-photo { position: relative; width: 100px; height: 100px; }.status-photo img { width: 100%; height: 100%; border-radius: 100%; object-fit: cover; }.status-photo.status { width: 20px; height: 20px; border-radius: 50%; background-color: rgb(255, 60, 0); border: 2px solid white; bottom: 0; right: 10px; position: absolute; }
 <div class="status-photo"> <img src="https://images.unsplash.com/photo-1438761681033-6461ffad8d80?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8cGVyc29ufGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60" /> <div class="status" /> </div>

The answers above were helpful. But, a more responsive way to do it is to user percentages:

.status-photo {
  display: block;
  position: relative;
  width: auto;
  height: auto;
}

.status-photo img {
  width: 100%;
  height: 100%;
  border-radius: 100%;
  object-fit: cover;
}

.status-photo .status-online {
  width: 20%;
  height: 20%;
  border-radius: 50%;
  background-color: rgb(255, 60, 0);
  border: 1px solid white;
  bottom: 0%;
  right: 0%;
  position: absolute;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM