CSS 垂直居中

40 阅读1分钟

方案一

父元素定义 display:table; ,子元素定义 display: table-cell; vertical-align: middle;

html

<div class="div-contain">
  <md-icon class="icon-middle">new</md-icon>
</div>

css

.div-contain {
  dispaly: table;
  width: 100%;
  height: 100%;
}
.icon-middle {
  display: table-cell;
  vertical-align: middle;
}

方案二

HTML

<div id="box">
    <div id="child">test vertical align</div>
</div>

CSS

#box {
    width: 300px;
    height: 300px;
    background: #ddd;
    position: relative;
}
#child {
    background: orange;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
}