Fred
Fred

Reputation: 147

How to align div in center of a page?

I want a div which is centered vertically and horizontally i.e. in the centre of a page. I tried position: absolute and making the div's top right bottom left 0! But the problem is when i zoom in the page it overlaps with other header and other divs! PLEASE HELP ME! How can i position the div at centre of a page without overlapping other divs while zooming in the page?

Like i have tried:

.center{
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
 }

Upvotes: 8

Views: 46216

Answers (7)

CodeToLife
CodeToLife

Reputation: 4141

2020.4.23
coping from real project

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


<div id="id01" style="width: 50%;height: 30%;background-color: red; margin: auto;">
</div>

Upvotes: 1

Ajay
Ajay

Reputation: 975

This is Your HTML Body
<div class="testbox"> <!-- Your div body --> </div>

This is Your CSS
.testbox { width: 800px; margin: 0 auto; position: absolute; top: 0; bottom: 0; left: 0; right: 0; }

Upvotes: 0

EyWN
EyWN

Reputation: 137

Flex is the best solution, perfect position.

If you want this for a loader, just do a full size div with position fixed and use flex for the div content.

Flex guide https://css-tricks.com/snippets/css/a-guide-to-flexbox/

body, html {
  height:100%
}

body {
  display:flex;
  margin:0;
  flex-direction:column;
}

.mydiv {
  margin:auto;
}
<div class="mydiv">test</div>

Upvotes: 2

shiva krishna
shiva krishna

Reputation: 222

To horizontally center a block element (like div), use margin: auto

.center {
    margin: auto;
    width: 60%;
    border: 3px solid #73AD21;
    padding: 10px;
}
<div class="center">
  <p><b>Note: </b>Using margin:auto will not work in IE8, unless a !DOCTYPE is declared.</p>
</div>

Upvotes: 2

Hash
Hash

Reputation: 8020

Try,

html{
  height:100%;
}
body
{ height:100%;
  background-color: #fcfcfc;

}
.center
{
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100px;
  height: 100px;
  background-color: #ccc;
  border-radius: 3px;
}
<div class="center"></div>

Upvotes: 7

Chandra Shekhar
Chandra Shekhar

Reputation: 3749

Try This

HTML

<div class="center">
  Lorem ipsum dolor sit amet, 
</div>

CSS

html,body{
  height:100%;
}
.center{
  position: relative;
  top:50%;
  left:50%; 
}

Link for reference

Hope this Helps..

Upvotes: 1

terryeah
terryeah

Reputation: 593

html, body {
  height:100%;
}

.center {
  border: 2px solid blue;
  margin: auto;
  position: relative;
  text-align: center;
  top: 50%;
  width: 20%;  
}
<div class="center">
  <p>Test Text</p>
</div>

Upvotes: 4

Related Questions