如何在圈子中显示用户个人资料图片?

har*_*h4u 27 css image

我正在开发一个网站,用户的个人资料图片需要以圆圈形式显示.此网站上有许多圈子,圈子大小可能会有所不同.

我可以正确显示方形图像,但垂直和水平图像我遇到问题.

我必须使用以下标准将图像显示在一个圆圈中:

  • 假设图像大小是500x300.图像应从右侧和左侧裁剪100px,以便显示图像的中心.现在图像应该是300x300居中的.然后我需要从该图像中制作一个圆圈.或者使用CSS隐藏图像左右两侧的100px.
  • 如果图像大小是300x500,则应使用CSS隐藏顶部和底部区域

我该怎么做才能解决这个问题?如果可能的话,CSS-only答案对我来说是最好的.

Luk*_*uke 53

background-size

MDN - CSS技巧 - 我可以使用

由于图像大小是可变的,您需要确保它们cover是div以及在其中center编辑.

添加border-radius: 50%;将为您提供圆圈效果.

.user {
  display: inline-block;
  width: 150px;
  height: 150px;
  border-radius: 50%;

  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}

.one {
  background-image: url('http://placehold.it/400x200');
}

.two {
  background-image: url('http://placehold.it/200x200');
}

.three {
  background-image: url('http://placehold.it/200x400');
}
Run Code Online (Sandbox Code Playgroud)
<div class="user one">
</div>

<div class="user two">
</div>

<div class="user three">
</div>
Run Code Online (Sandbox Code Playgroud)

实际上,您不希望每个图像都有一个类,因此您需要在标记中使用内联样式指定它:

<div class="user" style="background-image:url('path/to/user/img.png')"></div>
Run Code Online (Sandbox Code Playgroud)

object-fit

MDN - CSS技巧 - 我可以使用

更新的替代方法是object-fit在常规<img>标记上使用该属性.这在IE或旧版Edge中不起作用.

.user {
  display: inline-block;
  width: 150px;
  height: 150px;
  border-radius: 50%;

  object-fit: cover;
}
Run Code Online (Sandbox Code Playgroud)
<img src="http://placehold.it/400x200" class="user">
<img src="http://placehold.it/200x200" class="user">
<img src="http://placehold.it/200x400" class="user">
Run Code Online (Sandbox Code Playgroud)


Luu*_*obs 7

将图像设置为背景,居中.

<div class="image"></div>
Run Code Online (Sandbox Code Playgroud)

CSS:

.image{
  width: 300px;
  height: 300px;
  border-radius: 50%; /*don't forget prefixes*/
  background-image: url("path/to/image");
  background-position: center center;
  /* as mentioned by Vad: */
  background-size: cover;
}
Run Code Online (Sandbox Code Playgroud)

小提琴