首页 > 解决方案 > 在 svg 上放置文本

问题描述

我正在尝试将“s”移动到灰色框所在的位置。我尝试在 css 中这样做,但这破坏了响应能力

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">

<section class="justify-content-center d-flex">
  <div class="container position-absolute h-100">
    <div class="row h-100 justify-content-center align-items-center">
      <svg width="200" height="200" viewBox="0 0 600 600" fill="none" xmlns="http://www.w3.org/2000/svg">
        <rect width="600" height="600" fill="#C4C4C4"/>
      </svg>
    </div>
    <h1 class="row justify-content-center align-items-center">s</h1>
  </div>
</section>

在此处输入图像描述

标签: svgbootstrap-4

解决方案


如果您希望您svg以任何尺寸设置显示并响应,那么您需要将h1div类设置.position-absolute为覆盖您的svg,其父div类设置为.position-relative.

请参阅下面的示例代码。

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">

<section class="py-3">
  <div class="container">
  
    <div class="position-relative">
      <svg viewBox="0 0 600 600" xmlns="http://www.w3.org/2000/svg">
        <rect width="600" height="600" fill="#C4C4C4"/>
      </svg>
      <div class="d-flex justify-content-center align-items-center position-absolute w-100 h-100 p-3" style="top:0;left:0;">
        <h1>S</h1>
      </div>  
    </div>
 
  </div>
</section>

还有其他选项,例如将svg用作背景图像,或css将文本置于svg. 有很多方法可以做到。

但是,使用 bootstrap 4 flex 实用程序,我上面的代码是我将如何处理它以响应本svgviewBox比率。


推荐阅读