解决方法
以下是3种非常好的技术,用于将容器中的子项垂直居中 – 即使您不知道子元素的高度.前2个来自
this CSS-tricks article
<div class="block"> <div class="centered"> Some text </div> </div>
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; }
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; }
(相关)CSS:
.block { background: orange; height: 300px; display: flex; align-items: center; }