How can center div horizontally and vertically

There is 3 Options for center div.

For that you need to create HTML first.

HTML

<div class="my_div">Hello</div>

CSS

.my_div{
  width:100px;
  height:100px;
  background:yellow;
  text-align:center;
  line-height:100px;
  position:absolute;
  top:50%;
  left:50%;
  margin-top:-50px;
  margin-left:-50px;
}

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”QMXQgB” default_tab=”css,result” user=”pradeepanvi”]See the Pen center div horizontally and vertically by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

HTML

<div class="my_div">Hello</div>

CSS

.my_div{
  width:100px;
  height:100px;
  background:yellow;
  text-align:center;
  line-height:100px;
  position:absolute;
  top:50%;
  left:50%;
  transform:translate(-50%, -50%);
}

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”RZzQjV” default_tab=”css,result” user=”pradeepanvi”]See the Pen center div horizontally and vertically 02 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

HTML

<div class="table">
  <div class="table_cell">
    <div class="my_div">Hello</div>
  </div>
</div>

CSS

.table{
  display:table;
  width:100%;
  height:500px;
}
.table .table_cell{
  display:table-cell;
  vertical-align:middle;
  text-align:center;
}
.my_div{
  width:100px;
  height:100px;
  background:yellow;
  text-align:center;
  line-height:100px;
  display:inline-block;
}

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”wqLypj” default_tab=”css,result” user=”pradeepanvi”]See the Pen center div horizontally and vertically 03 by Pradeep Kumar (@pradeepanvi) on CodePen.[/codepen_embed]

Leave a Reply

Your email address will not be published. Required fields are marked *