CSS - Horizontally and Vertically centering a Div


#1

Hi Everyone,

Can you help me understand why margin-left: -150px; and margin-top: -150px; perfectly aligns my div vertically and horizontally, while margin: auto; doesn’t?

Here’s my code:



#2

I don’t know if this will solve your problem or not, but as far as i know to make the “margin:0 auto” work we need to define the width of block type element, and it wont work if your container width is the same as the parent width.

This code just work to make your element centered
Here’s my code:
.center {
width: auto;
height: auto;
position: relative;
top: 50%;
text-align: center;
}

And if you want to use “margin: 0 auto” , this work i think
Here’s my code:
.center {
width: 500px;
height: auto;
position: relative;
top: 50%;
margin: 0 auto;
}

.img {
text-align: center;
}

.search {
text-align: center;
}


#3

a little tip if you add this

* {
border: 1px solid red;
}

to your styles during development, it’ll highlight the widths of your containers.


#4

It works because you are hard coding i.e. manually inserting in specific margins for your top and left. By using negative values you are essentially going the opposite direction of the margin specified e.g. margin-left: -150px will push the DOM element to the left rather than push it from the left(going right).

As far as I can tell with your code, you set the body of your HTML with a width of 100%, but not the height. So try adding in height of 100% which should help with your margin auto, or try using margin: 0 auto, which will set the top and bottom margins to 0 and auto center the left and right based on the container it is in. Hope this helps answer your question :slight_smile:


#5

Thanks for the input all.

I have no clue why I can’t get this right. This must be the most complicated thing I came across in this exercise :sweat_smile:

Here’s what I have in my code:
body{ background-color: white; font-family: Arial, sans-serif; width: 100%; height: 100%; }

.center { width: auto; height: auto; position: absolute; top: 50%; left: 50%; margin: 0 auto; text-align: center; }

And here’s how that looks awfully not centered at all:

Any input is much appreciated!


#6

@Yuri You need to remove **left: 50%** from your code. You are essentially pushing the .center class 50% from the left, which is exactly why the the Google image appears to be offset even more than the normal position.

Try using a flexbox or using text-align for the .center class


#7

Thank you. I’ve found the issue.
It was perfectly centered inside the Div but the div itself wasn’t centered on the page. As you can see below, the navbar is appearing to the right of my main div:

Changing my navbar style to display: inline-block solved this frustrating issue I was seeing.

Many thanks for the help!