-1

.try {
    background-color: aqua;
    width: 100px;
    height: 100px;
    margin: 0 auto;
    margin-top: 50%;
    position:relative;
}
<div class="try"></div>

Hello sorry for a dumb question, but is it possible to make this div go to the center of the page without using flexbox maybe?

Finrod
  • 2,425
  • 4
  • 28
  • 38
Edgaras
  • 69
  • 4

3 Answers3

3

You need to set top and transform property in css insted of margin-top.

top: 50%;
transform: translateY(-50%);

.try {
  background-color: aqua;
  width: 100px;
  height: 100px;
  margin: 0 auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

body,
html {
  height: 100%;
}
<div class="try"></div>
Nandita Sharma
  • 13,287
  • 2
  • 22
  • 35
  • This is a great way to do that, but it does mean that any content after this will still be pushed as if the element wasn't transformed, but I guess thats not important for a full center. Although I still think a `flexbox` around it and a `margin: auto` is the quickest way and its very well supported now. – somethinghere Jun 25 '18 at 07:35
  • he don't *need* to use `top` .. margin-top will do exactly the same as top since the element is position:relative – Temani Afif Jun 25 '18 at 07:45
  • oh i didnt know that. Thanks @TemaniAfif :) – Nandita Sharma Jun 25 '18 at 07:46
-1

You declare margin-top: 50% that's why div goes below 50% down.

.try {background-color: aqua;
            width: 100px;
            height: 100px;
            margin: 25% 0 25% 0;
            position:relative;
        }
<div class="try"></div>
-1

this is because you set top marging to 50%.set all margins to 50%.

raja
  • 83
  • 2
  • 3
  • 16