简体   繁体   中英

How to align an a tag vertically?

I see this pattern often.

Can I use it to center align a HTML tag?

.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. 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.

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 .

If you want to know about flex , try to go here 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.

Please check this https://jsfiddle.net/5sLef3pz/

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

Its related 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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