html - 如何使用 CSS 确保图像不超过可用的浏览器高度?

标签 html css

我正在使用 Bootstrap Freelancer 主题 ( https://startbootstrap.com/themes/freelancer/ ) 构建一个页面。

我想确保忍者的图像填满可用空间,但又不会超出页面底部。 (我在容器 DIV 上加了一个红色边框,以便更容易看到发生了什么。)

我如何设置它,使其始终调整到最大,但不裁剪任何图像?

我尝试过使用 object-fill:contain 但没有用。

enter image description here

此外,如果我尝试设置 height:80% 或其他设置,它会出于某种原因将图像调整得更小 - 不确定为什么?

enter image description here

这是代码:

<header class="masthead bg-primary text-white text-center">
<div class="container d-flex align-items-center flex-column" style="border: 1px solid red">

  <!-- Masthead Avatar Image -->
  <img class="masthead-avatar mb-5" style="margin-top:-100px;" src="img/magic-assassin.svg" alt="">

  <!-- Masthead Heading -->
  <h1 class="masthead-heading text-uppercase mb-0">Magic Assassin</h1>

  <!-- Icon Divider -->
  <div class="divider-custom divider-light">
    <div class="divider-custom-line"></div>
    <div class="divider-custom-icon">
      <i class="fas fa-star"></i>
    </div>
    <div class="divider-custom-line"></div>
  </div>

  <!-- Masthead Subheading -->
  <p class="masthead-subheading font-weight-light mb-0">Nu-Disco - Edits - Balearic</p>

</div>
</header>

这是CSS:

.masthead {
  padding-top: calc(6rem + 74px);
  padding-bottom: 6rem;
}

.masthead .masthead-heading {
  font-size: 2.75rem;
  line-height: 2.75rem;
}

.masthead .masthead-subheading {
  font-size: 1.25rem;
}

    .masthead .masthead-avatar {


    }

最佳答案

您只需将 img 设置为 100vh。请记住,这也考虑了搜索栏的高度,因此您可能会被剪掉一点。为了解决这个问题,我通常只设置为 95vh。这会处理任何中断。

img {
  height:100vh;
}

在你的例子中,因为你正在使用 calc 作为你的高度,你可以用同样的方式应用这个方法,就像这样:

img {
  height:calc(100vh-74px); // I'm assuming this is the height of your nav, given your css
}

关于html - 如何使用 CSS 确保图像不超过可用的浏览器高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56684662/

相关文章:

html - 让 <divs> 彼此对齐

html - 我在 Angular 中使用 mdbootstrap 下拉菜单时出现问题

javascript - 带有文本区域内容的警报(HTML 到 JavaScript)

css - 两个宽度为 100% 的分隔 div 不匹配

html - CSS:在段落中穿插图像

jquery - Owl Carousel css 设置为显示 :none when page has loaded

html - 每个其他 div 的 child 的第 n 个 child

python - 导入错误 : cannot import name timezone pythonanywhere

css - 如何在悬停时及时摇动图像

javascript - 有什么方法可以对用户缩放事件使用react吗?