首页 > 解决方案 > 将图像放入 Bootstrap SVG

问题描述

所以我正在用 Bootstrap 5 构建一个网页,我正在使用的元素之一(来自 BS5 模板)是这个

    <div class="col" data-aos="fade-up" data-aos-delay="200">
      <div class="card shadow-sm">
        <svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">Thumbnail</text></svg>

        <div class="card-body">
          <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
          <div class="d-flex justify-content-between align-items-center">
            <div class="btn-group">
              <button type="button" class="btn btn-sm btn-outline-secondary">Learn More</button>
            </div>
          </div>
        </div>
      </div>
    </div>

如您所见,上面有一个svg带有rect内部的标签。我想显示一个图像来代替rect(或在其中,只需要它与 的尺寸相同rect),同时保留当前显示的文本rect

现在我知道为了在 an 中显示图像,svg您需要clip path使用所需的形状定义 a ,但这看起来像是为更好的实现而编写的。

谁能指出我如何在rect不改变尺寸的情况下将图像放置在原处或原处,并且仍然保留显示的文本?

标签: htmlcsstwitter-bootstrapsvgbootstrap-5

解决方案


您可以简单地使用<image>标签,通过设置width和/或heightas 100%- image 将填充整个容器区域。

 <svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false">
      <title>Placeholder</title>
      <rect width="100%" height="100%" fill="#55595c" />
      <image href="https://www.wpbeginner.com/wp-content/uploads/2018/12/svgnoqualityloss.png" width="100%"/>
      <text x="50%" y="50%" fill="#eceeef" dy=".3em">Thumbnail</text>
    </svg>

JSFiddle:https ://jsfiddle.net/rcuq7sLb/6/

您还可以使用图像的宽度和高度,例如height: 100%

JSFiddle:https ://jsfiddle.net/rcuq7sLb/7/


推荐阅读