-1

I am trying to center a div element. It seems in my code that all is right but the element is not being centered properly Where did I wrong? If i try to center it by using flexbox then it is centered properly. Where is the wrong of positioning property?

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  width: 200px;
  height: 39px;
  border: 1px solid red;
  position: relative;
}

.cntr {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background-color: blue;
  width: 35px;
  height: 35px;
}
<div class='container'>
  <div class='cntr'>
  </div>
</div>
Mirajul Momin
  • 157
  • 1
  • 17

2 Answers2

0

You can use a flexbox instead of absolute positioning which will keep the document flow intact.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  width: 200px;
  height: 39px;
  border: 1px solid red;
  display: flex;
  justify-content: center; /* Horizontal alignment */
  align-items: center; /* Vertical alignment */
}

.cntr {
  background-color: blue;
  width: 35px;
  height: 35px;
}
<div class='container'>
  <div class='cntr'>
  </div>
</div>
Gerard
  • 15,418
  • 5
  • 30
  • 52
0

Use flexbox Here's the code html:

<div class="parent">
  <div class="child">

  </div>
</div>

css:

.parent{
  background: #000;
  width:100%;
  height:100%;
  display:flex;
  justify-content:center;
  align-items:center;

}
.child{
  background: #ff0;
  width:100px;
  height:100px;
}

Demo: https://jsbin.com/duxakey/edit?html,css,output

id3vz
  • 460
  • 4
  • 15