简体   繁体   English

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

[英]Vertical align inside anchor tag without using flex

As I said in title. 正如我在标题中所说。 I have to centering content inside an anchor tag. 我必须将内容放在锚标记内。 I can use line-height, but some of them contain pseudo element so I am finding another approach to gain what I need. 我可以使用line-height,但是其中一些包含伪元素,因此我正在寻找另一种获取所需内容的方法。 I am using flexbox, but I am told that's abusing way to use. 我正在使用flexbox,但有人告诉我这是滥用方式。 Could you please give me some suggestion? 你能给我一些建议吗? Please check code snippet as well. 请同时检查代码段。

If you have any more specific detail in this case, please tell me. 如果您在这种情况下还有其他详细信息,请告诉我。

Thanks in advance! 提前致谢!

 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> 

I am using flexbox, but I am told that's abusing way to use. 我正在使用flexbox,但有人告诉我这是滥用方式。

No, it's not abusive using Flexbox for this task, it's one of the things it does excellent. 不,使用Flexbox来完成此任务不是滥用,这是它出色的一件事。

The only reason not to, is to support very old browsers that doesn't support it, which Paulie D's answer has an alternative for. 不这样做的唯一原因是,支持不支持它的非常老的浏览器, Paulie D的答案是另一种选择。


Updated 更新

If you can wrap the text inside the anchor, you can also center it using transform: translate 如果可以将文本包装在锚点内,也可以使用transform: translate其居中transform: translate

 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; } 
 <a href="#"><span>text</span></a> <a href="#" class="without-pseudo"><span>text</span></a> 

Use CSS Tables 使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM