简体   繁体   English

如何垂直对齐标签?

[英]How to align an a tag vertically?

I see this pattern often. 我经常看到这种模式。

Can I use it to center align a HTML tag? 我可以使用它来使HTML标签居中对齐吗?

.pattern {
  top: 50%;
  transform: translateY(-50%);
}

How does it work exactly? 究竟如何运作?

To answer the question of what the positioning does: - when you set an element to fixed with a top and left of 50%, that sets the element to display with the top left corner at that position within the viewport. 要回答有关定位功能的问题:-当您将元素设置为固定的顶部和左侧为50%时,这会将元素设置为以左上角在视口中的该位置显示。 So therefore the top left corner is centered vertically and horizontally. 因此,左上角垂直和水平居中。 But only the top left corner is centered within the viewport, so what the remaining styling does is center the element relative to that point. 但是只有左上角在视口内居中,因此其余样式将元素相对于该点居中。 This is usually done by translating the element by 50% of its height and 50% of its width, so that now the center of the element is in the centered position. 通常,这是通过将元素平移其高度的50%和宽度的50%来完成的,因此,现在元素的中心处于居中位置。

The following demonstrates this: 以下内容说明了这一点:

  .centered{
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transform: -webkit-translate(-50%, -50%);
    transform: -moz-translate(-50%, -50%);
    transform: -ms-translate(-50%, -50%);  
  }

To show in pictures (please excuse the dodgy quality of the images) 在图片中显示(请原谅图像的模糊质量) 在此处输入图片说明

Try this way: 尝试这种方式:

 body{ margin:0; } .wrapper { position: relative; height: 100vh; } .pattern { top: 50%; transform: translateY(-50%); position:relative; } 
 <div class="wrapper"> <a class="pattern" href="#">Demo Text</a> </div> 

 *{margin:0; padding: 0;} .wrapper{ width: 100vw; height: 100vh; display: flex; align-items: center; } 
 <div class="wrapper"> <a href="#">Demo Text</a> </div> 

I would like to recommend to use flex . 我建议使用flex

If you want to know about flex , try to go here https://codepen.io/enxaneta/pen/adLPwv?q=flex&limit=all&type=type-pens 如果您想了解flex ,请尝试转到此处https://codepen.io/enxaneta/pen/adLPwv?q=flex&limit=all&type=type-pens

You can use flex for center aligning an element both horizontally and vertically. 您可以使用flex将元素水平和垂直居中对齐。

Please check this https://jsfiddle.net/5sLef3pz/ 请检查此https://jsfiddle.net/5sLef3pz/

<div class="flexbox-container">
    <div class="flex-item">flex item centered</div>
</div>

Its related CSS 相关的CSS

.flexbox-container {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    width: 300px;
    height: 300px;
    border: 1px solid;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;

    align-items: center;
    justify-content: center;
}

.flex-item {
  flex: 0 0 auto;
}

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

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