3

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

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278

2 Answers2

3

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

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • Thanks a lot, exactly what I was looking for. Appreciate your help! –  Jun 11 '14 at 09:34
  • What would I do if I wanted to add another section beneath this one? Exactly the same, just you have to scroll down to see it. –  Jun 11 '14 at 09:56
  • I'd like to have multiple sections beneath each other. Whenever I add content after this div/section it appears on the right of this one and I would like it to appear below it, if that makes sense? –  Jun 11 '14 at 10:04
  • @Viroe yeah it is happening because of `display: table-cell`. Let me check the issue. I am quite busy here right now. – Mr_Green Jun 11 '14 at 10:30
  • @Viroe I am not able to get your required layout with `display: table-cell`. So, I used transform which supports IE9+. go with this solution if you don't care about support in IE8. [**Fiddle**](http://jsfiddle.net/venkateshwar/xB84z/10/). Hey IE8 doesn't support `vh` unit. So, I am presuming you can go with this :) – Mr_Green Jun 11 '14 at 11:13
  • That's great! Thanks for taking the time to help me out! –  Jun 11 '14 at 11:24
3

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;

Community
  • 1
  • 1
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278