To center an element both vertically and horizontally: position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; But if you would like to understand how I came to these solutions, read further for more explanation.
To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.
Use the following CSS:
.centered {
position: fixed;
top: 50%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
}
Change position:absolute
to position: fixed
and you should be good to go!
When you say position - absolute, the reference div is the parent div that has a position - relative. However if you say position -fixed, the reference is the browser's window. which is wat you want in your case.
In the case of IE6 i guess you have to use CSS Expression
If you don't want to change your element's position to fixed
, here is a solution with keeping your element absolut
.
Since CSS's calc()
is supported by all browsers now, here a solution using calc()
.
#main {
width: 140px;
height:100px;
border: 1px solid Black;
text-align: left;
position: absolute;
top: calc(50vh - (/* height */100px / 2));
left: calc(50vw - (/* width */140px / 2));
}
A bit more complex way is to use multiple outer boxes. This method works well with or without hard coded width/height of the middle box (background colors added just to show what each box does):
/* content of this box will be centered horizontally */
.boxH
{
background-color: rgba(0, 127, 255, 0.2);
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
display: flex;
flex-direction: column;
align-items: center;
}
/* content of this box will be centered vertically */
.boxV
{
background-color: rgba(255, 0, 0, 0.2);
height: 100%;
display: flex;
flex-direction: row;
align-items: center;
}
/* content of this box will be centered horizontally and vertically */
.boxM
{
background-color: lightblue;
padding: 3em;
}
<div>
some text in the background
</div>
<div class="boxH">
<div class="boxV">
<div class="boxM">
this div is in the middle
</div>
</div>
</div>
https://jsfiddle.net/vanowm/7cj1775e/
If you want display div in the middle regardless of the scroll position, then change position
to fixed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With