【问题标题】:Center CSS X button居中 CSS X 按钮
【发布时间】:2021-04-28 12:47:30
【问题描述】:

我一直在尝试使用 CSS 执行关闭按钮以关闭标签。 我使用此处描述的模式组合完成了此操作:Patterns for Closebuttons,以及用于创建 X Close Button using CSS 的纯 CSS 模式。

现在我的问题是: 我不明白为什么 X 不是完全居中的。 如果我将位置更改为我用于线条的任何宽度的 50%,它似乎很好,因此我得出的结论是它必须与线条的宽度有关。

我在这里写信是想看看是否有人可以向我解释一下。

'HTML
<button type="button" aria-label="Close">
  <span aria-hidden="true" class="close"></span>
</button>

'CSS
button {
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: 700;
  padding: 0px;
  background-color: rgb(192,192,192);
  border: none;
  color: white;
 text-decoration: none;
 height: 150px;
 width: 150px;
 border-radius: 50%;
}
button:hover {
  background-color: rgb(146, 146, 146);
  cursor: pointer;
}

.close {
  position: relative;
  /* right: 10px; */
  width: 60%;
  height: 60%;
}
.close:before, .close:after {
  position: absolute;
  content: ' ';
  height: 100%;
  width: 20px;
  background-color: rgb(255, 255, 255);
}
.close:before {
 transform: rotate(45deg);
}
.close:after {
  transform: rotate(-45deg);
}

为了简单起见,我创建了一个代码笔:Codepen link

【问题讨论】:

  • 一切看起来都很好,但只需要正确定位线条。 i.stack.imgur.com/MxiYj.png
  • 你只需要负补偿那些伪元素宽度的一半。

标签: html css


【解决方案1】:

只需将 flexbox 添加到 .close 类即可开始使用

.close {
  position: relative;
  width: 100%;
  height: 60%; // 100% means that both lines will take the entire space
  display: flex;
  align-items: center;
  justify-content: center;
}

.close:before, .close:after CSS 规则的宽度实际上是让两条线从中心开始水平“扩展”。

但是,当它们被旋转时,它们的起始位置与没有旋转时不同,这就是它们的对齐方式变得不居中的原因。您可以检查该项目,您会看到实际的盒子有一个空白空间,这是“旋转宽度”的空白空间。

考虑一个 x = 0 坐标(距离 CSS 框左边距的 0px),它是 CSS 框的水平起点;旋转元素将使内容从 x = 开始? (通常是内容宽度的一半)

你也可以通过设置一个负值margin-left 来解决这个问题,它的值是width 的一半,但是使用 flexbox 需要更少的维护(想象一下,与 UI/UX 人员一起工作告诉你改变它的尺寸)

【讨论】:

  • 谢谢,知道为什么一开始就没有居中吗?
  • @PatrickBender 请检查我更新的答案,我希望它会让事情更清楚:)
【解决方案2】:

.close:before, .close:after 上添加这个 CSS left:50%; margin-left:-10px;

.close:before, .close:after {
  position: absolute;
  content: ' ';
  height: 100%;
  width: 20px;
  background-color: rgb(255, 255, 255);
  left:50%;
  margin-left:-10px;
}

【讨论】:

    【解决方案3】:

    您好,尝试将其添加到您的跨度类中。关闭:

    display: flex;
    justify-content: center;
    align-items: center;
    

    当你的属性是相对的时,你不应该使用 right 或 left。

    【讨论】:

    • 谢谢,错过了跨度刚刚在按钮上的那个。任何想法为什么它不以开始为中心?
    • image.noelshack.com/fichiers/2021/17/3/… 如果你检查屏幕,你的 span 居中你可以看到它,但看不到你里面的东西。
    猜你喜欢
    • 2013-06-06
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 2015-04-02
    • 2012-02-05
    • 2012-01-05
    相关资源
    最近更新 更多