首页 > 解决方案 > span 应该具有子 img 的宽度和高度

问题描述

我目前有一个问题,我首先虽然是微不足道的(它可能是),但我不知道如何完成这项工作。我有一个span,它只是一个图像的包装,span实际上应该有子元素的widthand 。height默认情况下,宽度很好,但高度span不适合图像的高度。如果我将其更改为block,则高度很好,但宽度为 100%(这是意料之中的,因为它是一个block元素)。子图像的宽度和高度未知

编辑:

我确实试过inline-block了,但它没有按预期工作。我在下面的代码段中为此添加了一个切换,请试一试。

$('#toggleInline').click(function() {
	$('#removed').removeAttr("style");
});

$('#toggleBlock').click(function() {
	$('#removed').removeAttr("style");
	$('#removed').css('display', "block");
});

$('#toggleInlineBlock').click(function() {
	$('#removed').removeAttr("style");
	$('#removed').css('display', "inline-block");
});
img {
  /* just because the sample image is too large */
  width: 50%;
}

span.removed {
  border: 3px solid #f00;
  background: repeating-linear-gradient(
    45deg,
    #f00,
    #f00 10px,
    #fff 10px,
    #fff 20px
  );
}

span.removed img {
  opacity: 0.85;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="removed" id="removed">
  <img src="https://images.pexels.com/photos/1036371/pexels-photo-1036371.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260">
</span>

<div style="margin-top: 15px">
  <button id="toggleInline">
    display: inline (default)
  </button>

  <button id="toggleBlock">
    display: block
  </button>

  <button id="toggleInlineBlock">
    display: inline-block
  </button>
</div>

这是我期望的样子:

在此处输入图像描述

标签: htmlcss

解决方案


似乎如果一个元素display: inline-block;的子节点带有一个基于百分比的宽度,它会在display: block; 内部自动切换,这是有道理的,因为百分比与父元素的宽度有关(而不是与 100% 的尺寸有关图像)(基本上具有width: min-content;,使其成为循环依赖)。如果将图像的宽度设置为固定宽度,它会按预期工作,或者根本不指定宽度

想象一下,您当前的定义基本上是这样的:

爸爸:我和你一样宽,我的孩子。

孩子:爸爸,我是你的一半!

爸爸:但是等等,这把我的宽度缩小到一半,因为我完全吞没了你。

孩子:拜托爸爸,剩下的空间只有以前的一半。我需要收缩!

爸爸:不要退缩,否则整个事情会重新开始,我们最终都会0px变宽!

$('#toggleInline').click(function() {
	$('#removed').removeAttr("style");
});

$('#toggleBlock').click(function() {
	$('#removed').removeAttr("style");
	$('#removed').css('display', "block");
});

$('#toggleInlineBlock').click(function() {
	$('#removed').removeAttr("style");
	$('#removed').css('display', "inline-block");
});
img {
  /* just because the sample image is too large */
  width: 50%;
}

span.removed {
  border: 3px solid #f00;
  background: repeating-linear-gradient(
    45deg,
    #f00,
    #f00 10px,
    #fff 10px,
    #fff 20px
  );
}

span.removed img {
  opacity: 0.85;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><span class="removed" id="removed">
  <img src="https://images.pexels.com/photos/1036371/pexels-photo-1036371.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260">
</span>
</p>
<div style="margin-top: 15px">
  <button id="toggleInline">
    display: inline (default)
  </button>

  <button id="toggleBlock">
    display: block
  </button>

  <button id="toggleInlineBlock">
    display: inline-block
  </button>
</div>


推荐阅读