user2682289
user2682289

Reputation:

Having problems vertically and horizontally centering div

I'm having a little trouble centering a div both horizontally and vertically. I've had a quick look around and can't really make much sense of other answers, so I thought I would post my own question.

What I am looking to do is center my div with text horizontally and vertically however I need the container div to stay perfectly sized to the window.

Here is the css I'm having trouble with.

body{margin:0 auto;}

div#section1 {height: 100vh;background: black;}

Also, here's a link to JSFiddle, I couldn't post HTML in here for some reason, the "Post" button would grey out.

Thanks

Upvotes: 3

Views: 591

Answers (2)

Mr. Alien
Mr. Alien

Reputation: 157334

All you need to do is to use the block of code below with margin: auto; which is important there.. Rest, playing with CSS positioning will do the job for you.

I don't think there's much to explain here, just make sure you use position: relative; for the container element so that your absolute positioned element stays correctly

div#section1 {
    height: 20vh;
    background: black;
    width: 20vh;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

Demo

You can refer my other answer here which will explain you some other techniques to achieve vertical alignment, because horizontal is quiet easy using margin: auto;

Upvotes: 3

Mr_Green
Mr_Green

Reputation: 41832

same: use vertical-align: middle.

body {
    margin:0 auto;
    color:white;
    width: 100%;
    display: table;
}
div#section1 {
    height: 100vh;
    background: black;
    display: table-cell;
    vertical-align: middle;
}
.center {
    text-align: center;
}

Working Fiddle

Upvotes: 3

Related Questions