首页 > 解决方案 > 如何使不同大小的 div 保持相同的格式

问题描述

我们有一个带有背景图像、一些文本(h1 和 p)和一个号召性用语按钮的 Bootstrap Jumbotron,并且希望能够针对不同的视口缩放图像,但要保持格式相同。所以 div 将被视为图像。

我在这里开始了这个实验:https ://codepen.io/Codewalker/pen/xxKRLBd并尝试了转换和转换,但我无法让它正确显示。它一直表现得像一个响应式 div。

<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <img src="https://picsum.photos/id/1056/1424/562" alt="test" class="img-fluid">
      <div class="heroContent">
        <h1>Jumbotron H1 goes here</h1>
        <p class="pHero">
        This is the first line in the jumbotron.<br>
        The second line appears underneath the first line.
        </p>
        <button type="button" class="btn btn-primary">Chat With Us</button>
      </div>
    </div>
  </div>
</div>

.container {
  max-width:1424px;
}
.heroContent {
  position: absolute;
  top: 30%;
  left: 30%;
  transform: translate(-50%, -50%);
}

目标是让整个 div 本质上被视为图像,在不改变格式或布局的情况下全部缩放。

标签: htmlcsstwitter-bootstrapcss-transitionstransform

解决方案


试试出色的 CSS 纵横比框技巧。padding-top基本思想利用了浏览器计算的怪癖。如果使用基于百分比的值,它将与您可能期望的元素的宽度而不是高度相关。阅读更多:https ://css-tricks.com/aspect-ratio-boxes/

对于您的布局,我简化了标记,因此只有一个外部 div ( .postcard) 和一个包含所有内容 ( .heroContent) 的内部 div。

外部 div 得到position: relative,因为内部 div 将被绝对定位。然后像这样应用纵横比技巧:

.postcard {
  width: 1424px;
  padding-top: calc(562 / 1424 * 100%);
}

padding-top属性通过将高度除以宽度然后将该比率乘以 100% 来计算纵横比,以获得相对于宽度的正确高度(因为它是 padding-top)。现在外部容器将始终保持固定的高度/宽度纵横比。将图像作为背景应用到该 div。您的内部内容可以排列以覆盖该区域,如下所示:

.heroContent {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

要偏移内容的定位,请利用以下相同的怪癖padding-top

.heroContent {
  padding-top: 8%;
  padding-left: 8%;
}

请记住,padding-top它基于宽度,因为该值是百分比。现在您只需要将内容与 div 一起缩放。为此,请分配font-size相对于视口宽度的值:

.heroContent h1 {
  font-size: 3vw;
  margin-top: 0; /* this line removes the extra space you would get from default margin top on a heading element */
}

.pHero {
  font-size: 1.8vw;
}

.heroContent .btn {
  font-size: 1.2vw;
}

在全屏视图中运行代码片段并更改视口宽度以查看效果。希望有帮助!

.postcard {
  position: relative;
  width: 1424px;
  max-width: 100%;
  padding-top: calc(562 / 1424 * 100%);
  background-image: url('https://picsum.photos/id/1056/1424/562');
  background-repeat: no-repeat;
  background-position: left top;
  background-size: cover;
}

.heroContent {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  padding-top: 8%;
  padding-left: 8%;
}

.heroContent h1 {
  font-size: 3vw;
  margin-top: 0;
}

.pHero {
  font-size: 1.8vw;
}

.heroContent .btn {
  font-size: 1.2vw;
}
<div class="postcard">
  <div class="heroContent">
    <h1>Jumbotron H1 goes here</h1>
    <p class="pHero">
      This is the first line in the jumbotron.<br> The second line appears underneath the first line.
    </p>
    <button type="button" class="btn btn-primary">Chat With Us</button>
  </div>
</div>


推荐阅读