如何在<a> element, that is displayed as block

时间:2017-02-24 16:01:49

标签: html css

I have this code:

a {
  display: block;
  width: 231px;
  height: 52px;
  background-color: #ffffff;
  color: #0275d8;
  border: 1px solid #0275d8;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  font: 16px 'Lato', sans-serif;
}
<a href="#">some text</a>
</br>
<a href="#">some text that is bigger than in the first link</a>

Is there any way I could align the text vertically? Using paddings here is not a good idea, IMHO. Any help would be appreciate. Thanks.

3 个答案:

答案 0 :(得分:3)

您可以使用Flexbox并将文字与align-items: center对齐。

&#13;
&#13;
a {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 231px;
  height: 52px;
  background-color: #ffffff;
  color: #0275d8;
  border: 1px solid #0275d8;
  border-radius: 4px;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  padding-top: 15px;
  padding-bottom: 15px;
  font: 16px 'Lato', sans-serif;
}
&#13;
<a href="#">some text</a>
<br>
<a href="#">some text that is bigger than in the first link</a>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

我总是使用flexbox来做这种事情。用css布局内容真是太棒了。这是弹性框的a great reference

在这种情况下,您只需添加display: flex; justify-content: center; align-items: center;,然后移除margin-left: auto;margin-right: auto;

&#13;
&#13;
a {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 231px;
  height: 52px;
  background-color: #ffffff;
  color: #0275d8;
  border: 1px solid #0275d8;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
  text-align: center;
  padding-top: 15px;
  padding-bottom: 15px;
  font: 16px 'Lato', sans-serif;
}
&#13;
<a href="#"><span>some text</span></a>
</br>
<a href="#"><span>some text that is bigger than in the first link</span></a>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

我建议您更改为span并在里面添加一个表格单元格,您可以使用任何标记,例如a { display: table; width: 231px; height: 52px; background-color: #ffffff; color: #0275d8; border: 1px solid #0275d8; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; text-align: center; margin-left: auto; margin-right: auto; padding-top: 15px; padding-bottom: 15px; font: 16px 'Lato', sans-serif; } a span{ display:table-cell; vertical-align:middle; }

<a href="#"><span>some text</span></a>
</br>
<a href="#"><span>some text that is bigger than in the first link</span></a>
display:flex

{{1}}并不适用于所有导航仪,桌面和放大器表格单元格是容器内“垂直对齐”事物的最佳选择