user8167374
user8167374

Reputation:

position absolute to center in the middle of a div

Hello guys i am having trouble to center a div in the middle of the screen after setting the position to absolute , i dont want to use flexbox because of the browser compatibilities

<style>div{
height:200px;
width: 300px;
display:inline-block;
position: absolute;
background-color:red;
}
</style>
<div>
some content
</div>

https://codepen.io/anon/pen/KqWYQg

Upvotes: 1

Views: 856

Answers (4)

Ori Drori
Ori Drori

Reputation: 191916

You can use Absolute Horizontal And Vertical Centering, which is cross browser (works in IE8), and pretty simple:

html, body {
  height: 100%;
  margin: 0;
}

div {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  height: 200px;
  width: 300px;
  background-color: red;
  margin: auto;
}
<div>
  some content
</div>

Upvotes: 1

xxCodexx
xxCodexx

Reputation: 438

div{
    height:200px;
    width: 300px;
    display:inline-block;
    position: absolute;
    background-color:red;
    left:50%;
    transform: translateX(-50%); 
    }
<div>
some content
</div>

Use other browser's compatibility

Upvotes: 0

Peter Kota
Peter Kota

Reputation: 8340

You need to add left: 50%;, top: 50%; and transform: translate(-50%, -50%);. Don't forget to use the prefixes to cross browser compatibility.

div {
  height: 200px;
  width: 300px;
  position: absolute;
  background-color: red;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
<div>
  some content
</div>

Upvotes: 0

Carl Binalla
Carl Binalla

Reputation: 5401

Add left:50% and top:50% plus transform:translate(-50%, -50%).

This will center an element horizontally and vertically. This is also useful for responsive designing as the element will stay centered even if you resize the browser

div {
  height: 200px;
  width: 300px;
  display: inline-block;
  position: absolute;
  background-color: red;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div>
  some content
</div>

Upvotes: 4

Related Questions