使用 Tailwindcss 在 svg 圆圈内居中 div

Center a div inside an svg circle with Tailwindcss

我正在尝试将 29% 值的 div 元素置于 svg 圆圈内的中心。我尝试使用相对和绝对属性将它居中,但它似乎不起作用

<!-- Tailwind -->
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">


<!-- Body -->
<div class="relative bg-red-100">
  <svg width="120" height="120" viewBox="0 0 120 120">
            <circle cx="60" cy="60" r="54" fill="none" stroke="#e6e6e6" stroke-width="12" />
            <circle class="percent sixty" cx="60" cy="60" r="54" fill="none" stroke="#f77a52" stroke-width="12" pathLength="100" />
        </svg>
  <div class="absolute inset-0 text-5xl font-semibold text-gray-900" style="font-family: 'Titillium Web', sans-serif;">29%</div>
</div>

  1. 您需要通过添加 class w-min 来限制容器的宽度。否则它将默认跨越整个可用宽度,因为 div 是 block-level-element.

  2. 您需要向绝对定位元素添加以下 classes 以使其居中:top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2

  3. 您可以删除 inset-0 class,因为它对您没有任何作用

<!-- Tailwind -->
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">


<!-- Body -->
<div class="relative w-min bg-red-100">
  <svg width="120" height="120" viewBox="0 0 120 120">
            <circle cx="60" cy="60" r="54" fill="none" stroke="#e6e6e6" stroke-width="12" />
            <circle class="percent sixty" cx="60" cy="60" r="54" fill="none" stroke="#f77a52" stroke-width="12" pathLength="100" />
        </svg>
  <div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-5xl font-semibold text-gray-900" style="font-family: 'Titillium Web', sans-serif;">29%</div>
</div>

您没有定义父容器的width/height。一个更简单的方法也可以使用 flexbox 而不是 relative/absolute 定位。尤其是当涉及到容器内文本的垂直对齐时。

<!-- Tailwind -->
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">


<!-- Body -->
<div class="flex justify-center items-center bg-red-100 w-min">
  <svg width="120" height="120" viewBox="0 0 120 120">
            <circle cx="60" cy="60" r="54" fill="none" stroke="#e6e6e6" stroke-width="12" />
            <circle class="percent sixty" cx="60" cy="60" r="54" fill="none" stroke="#f77a52" stroke-width="12" pathLength="100" />
        </svg>
  <div class="absolute w-min flex items-center justify-center text-5xl font-semibold text-gray-900" style="font-family: 'Titillium Web', sans-serif;">29%</div>
</div>

您还可以在 div of 29% 中添加填充。

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">


<!-- Body -->
<div class="relative bg-red-100 ">
  <svg width="120" height="120" viewBox="0 0 120 120">
    <circle cx="60" cy="60" r="54" fill="none" stroke="#e6e6e6" stroke-width="12" />
    <circle class="percent sixty" cx="60" cy="60" r="54" fill="none" stroke="#f77a52" stroke-width="12" pathLength="100" />
  </svg>
  <div class="p-4 py-8 absolute inset-0 text-5xl font-semibold text-gray-900" style="font-family: 'Titillium Web', sans-serif;">29%</div>
</div>