【问题标题】:Center reponsive image inside a div在 div 中居中响应图像
【发布时间】:2017-03-20 18:54:10
【问题描述】:

我正在尝试将由锚标记包裹在 div 内的图像居中。我尝试使用 display flexbox 和 justify-content:center 在一定程度上工作的图像,但是图像的高度保持不变,而宽度相应地改变,所以当我从桌面缩小到移动时,压缩了图像......从而失去了它的质量。

我怎样才能使这张图片居中。

注意:我使用的是纯波本威士忌

这就是我所拥有的

HTML

<div class="project">
  <a class="project__thumb" href="{{ project.url }}" target="_blank">
   <img src="{{ site.baseurl }}img/{{ project.thumbnail }}">
  </a>
</div>

SCSS

.project{
    width: 80%;
    margin: 0 auto; /*center whole block for mobile*/
    height: auto;
    margin-bottom: 60px;
    border-radius: 2px;
    position: relative;

    a{
      display: flex;
      justify-content: center;
    }

    img{
        max-width: 100%; /*make image responsive*/
        height: auto; /*make image responsive*/
        border-radius: 2px;
        transition: opacity 0.25s ease-in-out;
    }
}

@include media ($tablet){
    .main__projects{
        @include span-columns(12);
    }

    .project{
        @include span-columns(6 of 12);
        @include omega(2n);
        margin-bottom: 50px;
    }
}

@include media ($desktop){
    .main__projects{
        @include span-columns(12);
    }

    .project{
      @include span-columns(4 of 12);
      @include omega(3n);
        margin-bottom: 100px;
    }

}

【问题讨论】:

  • 代码似乎工作正常,有什么问题?
  • 图像的高度保持不变,而宽度相应地改变。导致图像变得压缩和压扁......即使我已经让它响应了。

标签: css html centering neat


【解决方案1】:

这里有几个问题。第一个问题是您为 CSS 使用了错误的 cmets。对于 CSS,您需要使用 /* */ 包装 cmets。 // 用于注释 JavaScript。因为您使用的是 Javascript cmets,所以 imgheightborder-radius 属性将被忽略。

另一个问题是在锚标记上使用display:flex;,这将阻止响应式图像大小调整。这应该可以帮助您开始:

.project{
    width: 80%;
    margin: 0 auto; /* center whole block for mobile */
    height: auto;
    margin-bottom: 60px;
    border-radius: 2px;
    position: relative;
    text-align:center;
}
    .project a {
      display:inline-block;
    }  
    .project img{
        max-width: 100%; /* make image responsive */
        height: auto; /* make image responsive - THIS IS NOT NECESSARY */
        border-radius: 2px;
        transition: opacity 0.25s ease-in-out;
    }
<div class="project">
  <a class="project__thumb" href="{{ project.url }}" target="_blank">
   <img src="http://placehold.it/250x250">
  </a>
</div>

【讨论】:

  • 这似乎奏效了。我最初尝试了 text-align 但它也不起作用?为什么要删除height:auto
  • @samsos auto 是默认高度值。只有当其他 CSS 覆盖它时,您才需要它。
  • @APAD1 还有 1 个问题。如果我想垂直和水平对齐怎么办。当然 flex 选项是合适的
猜你喜欢
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 2014-03-06
  • 2014-05-27
  • 2015-09-23
  • 1970-01-01
  • 2017-08-20
相关资源
最近更新 更多