html - 在 Bootstrap 4 中裁剪和居中图像以圈出

标签 html css twitter-bootstrap image geometry

你能帮我把矩形图像裁剪成圆形,裁剪到中心吗?我需要将裁剪图像的宽度调整为列宽。

我的代码:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
    <div class="col-4">
      <img class="img-fluid rounded-circle" src="http://wallpaper.pickywallpapers.com/1920x1080/mark-wahlberg-front-profile.jpg" alt="">
    </div>

    <div class="col-8">Hello there!</div>
</div>

我的解决方案不起作用,并且是用我的图像椭圆制作的。感谢您的帮助。

最佳答案

这是通过伪元素填充设置的 1x1 纵横比的解决方案,计算基于父元素的宽度。您可以在下面找到详细的文章

JS用于计算图片宽高比。

if width/height == 1 - image is square
if width/height > 1 - image is wide
if width/height < 1 - image is narrow

在计算之后,如果需要应用 tallAndNarrow 类并为所有图像添加 loaded 类以显示不透明度淡入并且在高图像重新定位期间没有抖动

Height equals width with pure CSS http://www.mademyday.de/css-height-equals-width-with-pure-css.html

Maintain Aspect Ratio SASS Mixin https://css-tricks.com/snippets/sass/maintain-aspect-ratio-mixin/

function fixAspect(img) {
  var $img = $(img),
    width = $img.width(),
    height = $img.height(),
    tallAndNarrow = width / height < 1;
  if (tallAndNarrow) {
    $img.addClass('tallAndNarrow');
  }
  $img.addClass('loaded');
}
.circle {
  width: 100%;
  position: relative;
  border-radius: 50%;
  overflow: hidden;
  text-align: center;
}

.circle:before {
  display: block;
  content: "";
  width: 100%;
  padding-top: 100%;
}

.circle>img {
  position: absolute;
  height: 100%;
  left: 50%;
  transform: translateX( -50%);
  top: 0;
  right: 0;
  margin: 0 auto;
  bottom: 0;
  opacity: 0;
  transition: opacity .4s;
}

.circle>img.tallAndNarrow {
  width: 100%;
  top: 50%;
  transform: translateX(0) translateY( -50%);
  left: 0;
  height: auto;
}

.circle>img.loaded {
  opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet" />
<div class="col-4">
  <div class='circle'>
    <img src="http://wallpaper.pickywallpapers.com/1920x1080/mark-wahlberg-front-profile.jpg" alt="" onload='fixAspect(this);'>
  </div>

</div>
<div class="col-4">

  <div class='circle'>
    <img src="http://via.placeholder.com/150x350" alt="" onload='fixAspect(this);'>
  </div>
</div>

<div class="col-4">

  <div class='circle'>
    <img src="http://via.placeholder.com/150x150" alt="" onload='fixAspect(this);'>
  </div>
</div>

关于html - 在 Bootstrap 4 中裁剪和居中图像以圈出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46083615/

相关文章:

html - 这个语法: &lt;! ---->有什么用?

html - 为什么我的代码获取的是屏幕的宽度而不是父屏幕的宽度?

html - Bootstrap : centering content in Nav and changing default beavior on smaller screens

php - 在 php 中保存 Canvas 但在图像文件中没有数据

javascript - 如何在 JavaScript 中检索 html 元素的 id

html - 使用 CSS3 动画将 div 从屏幕顶部移动到底部?

html - css 代码桌面 View 和移动 View 不起作用

css - 用于解析器的 Rails 应用程序中的进度条

javascript - 单击 bootstrap 折叠时页面丢失当前位置

flash - 使用 Flash 和/或 HTML5 播放本地音频文件