如何用 CSS 制作十字标志红圈

How to make a cross sign red circle with CSS

我想在红圈里打叉号(X)

这是我的尝试:

.crosssign {
    display:inline-block;
    width: 22px;
    height:22px;
    -ms-transform: rotate(45deg); /* IE 9 */
    -webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
    transform: rotate(45deg);
}

.crosssign_circle {
    position: absolute;
    width:22px;
    height:22px;
    background-color: red;
    border-radius:11px;
    left:0;
    top:0;
}

.crosssign_stem {
    position: absolute;
    width:3px;
    height:9px;
    background-color:#fff;
    left:11px;
    top:6px;
}

.crosssign_stem2 {
    position: absolute;
    width:3px;
    height:9px;
    background-color:#fff;
    right:11px;
    top:6px;
}

但看起来像这样:

那么我怎样才能以正确的顺序放置 stem 来制作 X 符号呢?

HTML 也在这里:

<span class="crosssign">
<div class="crosssign_circle"></div>
<div class="crosssign_stem"></div>
<div class="crosssign_stem2"></div>
</span>

您的词干未按应有的方式显示的原因之一是您忘记将 position: relative 添加到父 .crosssign 元素。有一个更简单的方法来解决这个问题:

  • 使用 top: 50%; left: 50%; transform: translate(-50%, -50%) 技巧将词干垂直和水平居中
  • 确保 stem 和 stem2 的宽度和高度翻转(这样它们就相对于彼此旋转了 90 度)
  • 在父元素上应用transform: rotate(45deg)

而且,你不需要添加厂商前缀来CSS转换:今天所有的浏览器(甚至IE11)都支持无前缀版本。

这是一个概念验证示例:

.crosssign {
  display: inline-block;
  width: 22px;
  height: 22px;
  position: relative;
  transform: rotate(45deg);
}

.crosssign_circle {
  position: absolute;
  width: 22px;
  height: 22px;
  background-color: red;
  border-radius: 11px;
  left: 0;
  top: 0;
}

.crosssign_stem,
.crosssign_stem2 {
  position: absolute;
  background-color: #fff;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.crosssign_stem {
  width: 3px;
  height: 9px;
}

.crosssign_stem2 {
  width: 9px;
  height: 3px;
}
<span class="crosssign">
  <div class="crosssign_circle"></div>
  <div class="crosssign_stem"></div>
  <div class="crosssign_stem2"></div>
</span>

我建议您使用 flexbox 使圆圈中的项目居中。然后旋转两个茎。此外,您可以对两个词干使用相同的 class,因此 css 更轻。这是代码

.crosssign {
    display:flex;
    justify-content: center;
    align-items: center;
    width: 22px;
    height:22px;
    background-color: red;
    border-radius:11px;
}

.crosssign_stem {
    position: absolute;
    width:4px;
    height:11px;
    background-color:#fff;
    -ms-transform: rotate(-45deg); /* IE 9 */
    -webkit-transform: rotate(-45deg); /* Chrome, Safari, Opera */
    transform: rotate(-45deg);
}

.crosssign_stem.right {
    -ms-transform: rotate(45deg); /* IE 9 */
    -webkit-transform: rotate(45deg); /* Chrome, Safari, Opera */
    transform: rotate(45deg);
}
<span class="crosssign">
  <div class="crosssign_stem"></div>
  <div class="crosssign_stem right"></div>
</span>

干杯!

使用更短的代码,您可以使用包含 unicode 符号的伪元素获得相同的结果 U+00D7

.crosssign {
  display: inline-grid;
  place-content: center;
  aspect-ratio: 1;
  min-inline-size: 1.25em;
  border-radius: 50%;
  background-color: #d12021;
}

.crosssign::before {
  content: "\D7";
  color: #fff;
  font-weight: bold;
}
<span class="crosssign"></span>