微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – 垂直对齐方法

垂直对齐某些东西相对于它的元素尺寸的最佳方法是什么.截至目前,我只知道vertical-align:middle;在< tr>内工作良好.

是否还有其他方法可以帮助我们在程序上实现这一目标?

解决方法

以下是3种非常好的技术,用于将容器中的子项垂直居中 – 即使您不知道子元素的高度.前2个来自 this CSS-tricks article

标记(适用于所有方法):

<div class="block">    
    <div class="centered">
        Some text
    </div>    
</div>

解决方案#1:CSS表方法(FIDDLE)

CSS:

/* This parent can be any width and height */
.block {
  display: table;
   width: 100%;
   background: orange;
   height: 300px;
}


.centered {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
   background: pink;
}

解决方案#2:伪(‘Ghost’)元素方法(FIDDLE)

CSS:

/* This parent can be any width and height */
.block {
  text-align: center;
  background: orange;
  height: 300px;

}

/* The ghost,nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered,can
   also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
    background: pink;
}

解决方案#3:FlexBox(FIDDLE)

(相关)CSS:

.block {
   background: orange;
   height: 300px;
   display: flex;
   align-items: center;
}

原文地址:https://www.jb51.cc/html/228179.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐