设置图像高度与宽度相同

时间:2016-05-22 08:14:59

标签: jquery html css

我有一个图像被多次显示,图像被拍摄并具有随机高度。

我进行了设置,以便使用父div的37.5%显示图像。

这一直很好,直到我开始得到div的不规则高度,因为没有给出高度。我已经尝试将高度设置为37.5%,尽管设法在宽度变得像素时获得完全不同的值。

我只是想在不设置硬pixel值或任何其他类型的值的情况下使图像成为完美的框。

当前CSS

/* Doesn't work. */
width: 37.5%;

float: left;
margin-left: 6.25%;
margin-right: 6.25%;
margin-bottom: 6.25%;

正在编辑HTML图像

<img src="LINK" />
<!-- Gets edited using ^ CSS. -->

注意:允许使用jQuery。

1 个答案:

答案 0 :(得分:1)

这是2个样本,其中parent2的孩子有background-image: cover,这将保留图像的比例,而不是拉伸它,这是第一个样本。

.parent,
.parent2 {
  width: 60%;
  overflow: auto;
  margin-bottom: 10px;
}

.child {
  float: left;
  width: 37.5%;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
  .parent2 .child {
    background-size: cover;
  }

.child:after {
  padding-top: 100%;  /* 1:1 ratio = perfect square */
  display: block;
  content: '';
}
.child.nr1 {
  background-image: url(http://lorempixel.com/200/400/animals);
}
.child.nr2 {
  background-image: url(http://lorempixel.com/400/200/animals);
}
.child.nr3 {
  background-image: url(http://lorempixel.com/300/300/animals);
}
<div class="parent">
  <div class="child nr1"></div>
  <div class="child nr2"></div>
  <div class="child nr3"></div>
</div>

<div class="parent2">
  <div class="child nr1"></div>
  <div class="child nr2"></div>
  <div class="child nr3"></div>
</div>

使用img时,在标记中设置图像源/路径,这也可以使用div来完成,这是必需的,就像这样

.parent,
.parent2 {
  width: 60%;
  overflow: auto;
  margin-bottom: 10px;
}

.child {
  float: left;
  width: 37.5%;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
  .parent2 .child {
    background-size: cover;
  }

.child:after {
  padding-top: 100%;  /* 1:1 ratio = perfect square */
  display: block;
  content: '';
}
<div class="parent">
  <div class="child" style='background-image: url(http://lorempixel.com/200/400/animals);'
></div>
  <div class="child" style='background-image: url(http://lorempixel.com/400/200/animals);'
></div>
  <div class="child" style='background-image: url(http://lorempixel.com/300/300/animals);'
></div>
</div>

<div class="parent2">
  <div class="child" style='background-image: url(http://lorempixel.com/200/400/animals);'
></div>
  <div class="child" style='background-image: url(http://lorempixel.com/400/200/animals);'
></div>
  <div class="child" style='background-image: url(http://lorempixel.com/300/300/animals);'
></div>
</div>