css - 使用 CSS 将页面上的元素垂直居中?

标签 css

我需要在页面上将未知高度的元素垂直居中。

我可以将它相对于包含的 div 垂直居中:

.one {
  background: grey;
  width: 50%;
  position: relative;
  top: 50%; 
 transform: translateY(-50%); 
  margin: auto;
}
.cont {
  background: blue;
  height: 300px;
}

http://codepen.io/anon/pen/lfrJx

但是我无法让它在页面上垂直居中:

.one {
  background: grey;
  width: 50%;
  position: relative;
  top: 50%; 
 transform: translateY(-50%); 
  margin: auto;
}
.cont {
  background: blue;
  height: 100%;
}

http://codepen.io/anon/pen/gqLcB

最佳答案

放这个 CSS :)

.one {
  background: grey;
  width: 50%;
  position: relative;
  margin-top:auto;
  margin-bottom:auto;
  vertical-align:middle;
}
.cont {
display: table-cell;
  background: blue;
  width:100%;
}

关于css - 使用 CSS 将页面上的元素垂直居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26423700/

相关文章:

html - 在圆 css 之间画线

jQuery mmenu 移动页面内容

css - 需要图像反弹

html - Bootstrap 导航栏在某些设备上无法正确显示

css - 包含 col-xx-x 跨度时,Bootstrap <a> list-group-item 格式会中断

javascript - 使用 css/javascript 更改背景颜色

html - 向下移动/微移文本而不是图像

html - 是否可以在纯 CSS 中自动隐藏第 (a ~ MAX) 个子元素的所有范围?

html - 页面顶部的页眉间隙

html - 以其他 4 个 div 为中心的 div