killerprince182 killerprince182 - 4 months ago 10
HTML Question

Element not coming to center. I am using absolute?

div #introbox is not centering. I have used container as relative and introbox as absolute. I have set top,bottom,left and right as 0. Still box is not centring. I want to centre the introbox in the intropic.



html,body{
padding: 0;
margin:0;
}


.container{
width: 960px;
margin:0 auto;
position: relative;
}

#header{
width: 100%;
height: 120px;
border-bottom: 1px solid black;
}


#nav{
height: 55px;
border-bottom: 4px solid lightblue ;
}

#intro-pic{
height: calc(100vh - 181px);
width: 100%;
background: url("img/introbg.jpg") center fixed;
}

#intro-box{
height: 55vh;
width: 800px;
background: rgba(0,0,0,0.74);
border-radius: 15px;
position: absolute;
top: 0px;
bottom: 0px;
right: 0px;
left:0px;
}

<div id="header">
<div class="container">
Header
</div>
</div>

<div id="nav">
<div class="container">
Nav
</div>
</div>

<div id="intro-pic">
<div class="container">
<div id="intro-box">
sdfdsfds
</div>
</div>
</div>




Answer

Using transform:translate will work for any size div.

html,
body {
  padding: 0;
  margin: 0;
  height:100%;
}
.container {
  width: 960px;
  margin: 0 auto;
  position: relative;
  height:100vh;
}
#intro-box {
  height: 55vh;
  width: 800px;
  background: rgba(0, 0, 0, 0.74);
  border-radius: 15px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  /* vertical centering */
}
<div id="intro-pic">
  <div class="container">
    <div id="intro-box">
      sdfdsfds
    </div>
  </div>
</div>