首页 > 解决方案 > 在 css 中指定图像的高度不起作用

问题描述

我目前正在开发一个 django 博客。但是,我在帖子缩略图的大小方面遇到了一些困难。这是一张图片:

在此处输入图像描述

我用黄色标记的是图像应该如何填充空间。如您所见,宽度很好,但高度效果不佳。

这是代码:

{% extends 'base.html' %}
{% load static %}

{% block content %}
<style>
  img {
    height: 100%;
    width: 100%;
    
  }
</style>

        <!-- Post-->
        {% for obj in object_list %}
        <div class="row d-flex align-items-stretch">
          {% if not forloop.first and not forloop.last %}
          <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the image
          {% endif %}
          <div class="text col-lg-7">
            <div class="text-inner d-flex align-items-center">
              <div class="content">
                <header class="post-header">
                  <div class="category">
                    {% for cat in obj.categories.all %}
                    <a href="#">{{ cat }}</a>
                    {% endfor %}
                  </div>
                  <a href="{{ obj.get_absolute_url }}">
                    <h2 class="h4">{{ obj.title }}</h2>
                    </a>
                </header>
                <p>{{ obj.overview|linebreaks|truncatechars:200 }}</p>
                <footer class="post-footer d-flex align-items-center"><a href="#" class="author d-flex align-items-center flex-wrap">
                    <div class="avatar"><img src="{{ obj.author.profile_picture.url }}" alt="..." class="img-fluid"></div>
                    <div class="title"><span>{{ obj.author }}</span></div></a>
                  <div class="date"><i class="icon-clock"></i> {{ obj.timestamp|timesince }} ago</div>
                  <div class="comments"><i class="icon-comment"></i>{{ obj.comment_count }}</div>
                </footer>
              </div>
            </div>
          </div>
          {% if forloop.first or forloop.last %}
          <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the image
          {% endif %}
        </div>
        {% endfor %}
      </div>
    </section>

标签: htmlcssdjango

解决方案


<img>填充整个宽度和高度是默认行为,通常会丢失其纵横比。

在您的情况下没有发生这种情况,很可能是因为您object-fit: contain在 css 中设置了某个位置。

您可以删除object-fit: contain设置,也可以使用

  img {
    height: 100%;
    width: 100%;
    object-fit: fill !important; # fill is the default value.  
  }

推荐阅读