【问题标题】:How to display user profile image in circle?如何在圆圈中显示用户个人资料图像?
【发布时间】:2014-10-30 08:51:06
【问题描述】:

我正在开发一个网站,用户的个人资料图片需要显示在一个圆圈中。这个网站上有很多圈子,圈子的大小可能会有所不同。

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

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

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

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

【问题讨论】:

  • 你可以使用border-radius

标签: css image


【解决方案1】:

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

<div class="image"></div>

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;
}

fiddle

【讨论】:

  • 前缀不再是问题,除非你想支持像 Safari 4 这样的浏览器
  • @HashemQolami:是的,但比抱歉更安全;)
  • 另加background-size: cover;
【解决方案2】:

background-size

MDN - CSS Tricks - Can I Use

由于图像大小是可变的,因此您要确保它们 cover div 以及 centered 在其中。

添加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('https://via.placeholder.com/400x200');
}

.two {
  background-image: url('https://via.placeholder.com/200x200');
}

.three {
  background-image: url('https://via.placeholder.com/200x400');
}
<div class="user one">
</div>

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

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

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

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

object-fit

MDN - CSS Tricks - Can I Use

一种较新的替代方法是在常规 &lt;img&gt; 标记上使用 object-fit 属性。这在 IE 或更旧版本的 Edge 中不起作用。

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

  object-fit: cover;
}
<img src="https://via.placeholder.com/400x200" class="user">
<img src="https://via.placeholder.com/200x200" class="user">
<img src="https://via.placeholder.com/200x400" class="user">

【讨论】:

    【解决方案3】:
    <html>  
    <head>
    <style>
    #circle
    {
    border-radius:50% 50% 50% 50%;  
    width:300px;
    height:300px;
    }
    </style>
    </head>
    <body>
    <img src="skin-tone.jpg"
    id="circle">
    </body>
    </html>
    

    【讨论】:

      【解决方案4】:

      如果您使用的是引导程序,则可以使用 img-circle 类来执行此操作。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 2020-09-21
      相关资源
      最近更新 更多