在锚标签内垂直对齐而不使用flex

时间:2017-09-21 10:23:32

标签: html css css3 flexbox

正如我在标题中所说的那样。我必须将内容置于锚标签内。我可以使用行高,但其中一些包含伪元素,所以我找到另一种方法来获得我需要的东西。我正在使用flexbox,但我被告知滥用方法。你能给我一些建议吗?请检查代码段。

如果您在这种情况下有更具体的细节,请告诉我。

提前致谢!



a {
  align-items: center;
  border: 1px solid #fff;
  background: #000;
  color: #fff;
  display: flex;
  flex-direction: column;
  height: 80px;
  justify-content: center;
  text-decoration: none;
  width: 120px;
}

.without-pseudo:before {
  content: none;
}
  
a:hover {
  background: green;
}
  
a:before {
  content: ':before';
  display: block;
}

<a href="#">text</a>
<a href="#" class="without-pseudo">text</a>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

  

我正在使用flexbox,但我被告知滥用方法。

不,使用Flexbox执行此任务是,这是它做得非常好的事情之一。

唯一不支持的理由是支持那些不支持它的旧浏览器, Paulie D&#39> 答案可以替代

更新

如果您可以将文本包装在锚点内,您也可以使用transform: translate

将其居中

&#13;
&#13;
a {
  display: inline-block;
  border: 1px solid #fff;
  background: #000;
  color: #fff;
  height: 80px;
  text-decoration: none;
  width: 120px;
  vertical-align: top;
  text-align: center;
}

a span {
  position: relative;
  display: inline-block;  
  top: 50%;
  transform: translateY(-50%);
}

.without-pseudo span:before {
  content: none;
}
  
a:hover {
  background: green;
}
  
a span:before {
  content: ':before';
  display: block;
}
&#13;
<a href="#"><span>text</span></a>
<a href="#" class="without-pseudo"><span>text</span></a>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用CSS表

a {
  border: 1px solid #fff;
  background: #000;
  color: #fff;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  height: 80px;
  text-decoration: none;
  width: 120px;
}

.without-pseudo:before {
  content: none;
}

a:hover {
  background: green;
}

a:before {
  content: ':before';
  display: block;
}
<a href="#">text</a>
<a href="#" class="without-pseudo">text</a>

相关问题