如何在页面上垂直居中div?

时间:2017-02-12 12:58:33

标签: html css

如何将#box div垂直居中于页面中心?我试过vertical-align:middle;但它不起作用。您可以实时查看网站here

这是css:

iframe {
  position: fixed;  
  width: 100vw; 
  height: 100vh;  
  border: none; 
  margin: 0; 
  padding: 0; 
  overflow: hidden; 
  z-index: 999999;
}

body {
  background-color: #000;
}

#box {
  text-align: center;
  vertical-align: middle;
}

#link {
  color: #FFF;
}

#download {
  color: #FFF;
}

6 个答案:

答案 0 :(得分:8)

方法1(位置,转换 - 翻译):

* {
  padding: 0;
  margin: 0;
}
.parent {
  position: relative;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background-color: gray;
}
.child {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 10em;
  height: 5em;
  background-color: white;
  box-shadow: 1px 1px 10px rgba(0,0,0,.4);
}
<div class="parent">
  <div class="child"></div>
</div>

方法2(Flexbox):

* {
  padding: 0;
  margin: 0;
}

.parent {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  background-color: gray;
  display: flex;
}

.child {
  margin: auto;
  width: 10em;
  height: 5em;
  background-color: white;
  box-shadow: 1px 1px 10px rgba(0, 0, 0, .4);
}
<div class="parent">
  <div class="child"></div>
</div>

答案 1 :(得分:2)

你可以用flexboxes做到这一点:

html,body {
  height: 100%;
  min-height: 100%;
}
.Aligner {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  min-height: 100%;
}

.Aligner-item {
  max-width: 50%;
  background-color: red;
}
<div class="Aligner">
  <div class="Aligner-item">…</div>
</div>

答案 2 :(得分:0)

添加包装div;盒的包装

#box-wrapper {
    position: relative;
}
#box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

通过css-tricks.com/centering-css-complete-guide可以找到更详细的解释

答案 3 :(得分:0)

.parent {
  text-align: center;
  white-space: nowrap;
}     
.parent:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em;
}
.child {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

答案 4 :(得分:0)

<强> HTML

<div class="container"><div class="your-div"></div></div>

<强> CSS

body, html{
    display:table;
    height:100%;
    width:100%;
}
.container{
    display:table-cell;
    vertical-align:middle;
}
.container .your-div{
    width:150px;
    height:150px;
    background:green;
    margin:0 auto;   
}

答案 5 :(得分:0)

下面三行就足够了:

.container {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}