CSS- 锚点元素水平居中的方法

374 阅读1分钟

在本教程中,我们将在实例的帮助下,学习如何在Css中把一个锚点<a> 元素水平居中。

考虑一下,我们在div中拥有以下锚点元素。

<div class="container">
  <a href="https://google.com" class="link">Google</h1>
</div>

为了使锚元素水平居中,将display:flexjustify-content: center 添加到anchor 的CSS类中。

"justify-content: center "使锚点元素水平居中。

下面是一个例子。

<div class="container">
  <a href="https://google.com" class="link">Google</a>
</div>

CSS。

.link{
    display: flex;
    justify-content: center;
}

或者我们可以使用HTML中的style 属性为锚点元素添加内联样式。

<div class="container">
  <a href="https://google.com" style="display: flex;justify-content: center;">
   Google
  </a>
</div>

使用绝对位置使div水平居中

我们也可以使用css中的绝对定位,将锚点<a> 水平居中。

下面是一个例子。

<div class="container">
  <a href="https://google.com" class="link">Google</a>
</div>
.link{
   position:absolute;
   left:50%;
   transform:translateX(-50%);
}
  1. 在这里,我们在锚元素的css类中添加了position:absolute ,因此该元素脱离了正常的文档流程,被定位到其相对的父元素(例如:body或父元素)。

  2. left:50% 将该元素从其位置向右移动50%。

  3. translateX(-50%) 将元素从它的位置向左移动50%。