在另一个div中居中多个div

时间:2018-05-06 20:36:42

标签: html css

我想在div中水平和垂直居中3个div。我不能使用flexbox,因为后来更多的div和flexbox会使这些新的div混乱,但我不知道如何垂直居中

<div class="hero">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

.hero {
  width: 100vw;
  height: 100vh; 
  text-align: center;
}

.box {
    width: 250px;
    height: 350px;
    background: red;
    margin: 50px;
    display: inline-block;
}

2 个答案:

答案 0 :(得分:0)

在将它撞到中途之后,它仍然可以通过将其高度调高一半来使其居中:

.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

更新:(优先级为H):

html, body {
    height: 100%;
}
.hero {
    text-align: center;
    align-items: center;
    vertical-align: middle;
    justify-content: center;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.box {
    width: 250px;
    height: 350px;
    background: red;
    margin: 5px;
    top: 50%;
    position: relative;
    display: inline-block;
}

答案 1 :(得分:0)

html,body,div,table-cell{
width:100%;
padding:0;
border:0;
}

.hero {
  width: 100vw;
  height: 100vh;        
    display:table-cell;
    vertical-align:middle;
}

#a{
margin:0 auto;
display:block;
width:750px;
}

.box {
    width: 250px;
    height: 50vh;
    background: red; 
    display:inline-block;
    box-sizing:border-box;
    border:3px solid black;
     
    
    
    
    
   }
<div class="hero">
  <div id='a'>
     <div class="box"></div
     ><div class="box"></div
     ><div class="box"></div>
 </div>
</div>