1

I am relatively new to front-end dev so a bit lost as to how i can go about this. I created a container that contains a slider and some images. My supervisor has a huge screen so obviously there will be empty space at the bottom of the screen. So he doesn't want that. Instead he wants the container to be centered horizontally and vertically based on the size of the user's screen.

How can I do this properly with as minimal code as possible? I believe there is jQuery plugin but wanted to see if there is a better way or if doing this makes sense at all or not?

putvande
  • 15,068
  • 3
  • 34
  • 50
starbucks
  • 2,926
  • 9
  • 41
  • 53
  • for horizontal, make `margin-left` and `margin right` = auto. The vertical one will be tougher, you will probably end up with making html display as table cell, or some javascript trick. – MightyPork Aug 06 '13 at 12:32
  • possible duplicate of [Center a DIV horizontally and vertically](http://stackoverflow.com/questions/14123999/center-a-div-horizontally-and-vertically) – Brigand Aug 06 '13 at 12:56

3 Answers3

3

Due to the flow-based nature of CSS, without Javascript this can only be done if the vertical size of the centered element is fixed, by applying a position:absolute' andtop:50%` within a fixed container, and then use negative margin to offset the container. Click here for JSFiddle Sample.

Alternatively the same effect can be reached by using display:table-cell, but that's kind of messy and loses you a lot of flexibility. Sample already supplied in the other answer here so I'll save myself the effort :)

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
  • The first proposed option is quite messy: You must give the size, **and** adjust the negative margings according to it. Also note that `position: fixed` causes problems with some mobile browsers. – MightyPork Aug 06 '13 at 12:44
  • Fixed positioning is not a problem on mobile if you properly supply viewport meta-tags. – Niels Keurentjes Aug 06 '13 at 13:03
1

You can do it easily using a vertical-align property.

Since vertical-align works the desired way way only in a table cell, this trick with display property can give you the desired effect.

#yourDiv {

    // give it a size
    width: 100px;
    height: 100px;

    margin: 0 auto;
}

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

html {
    display: table;
}

body {    
    display: table-cell;
    vertical-align: middle;
}

See a fiddle with demo.

MightyPork
  • 18,270
  • 10
  • 79
  • 133
1

Try this:

HTML:

<div class="center"></div>

CSS:

.center {
   width: 300px;
   height: 300px;
   position: absolute;
   left: 50%;
   top: 50%; 
   margin-left: -150px;
   margin-top: -150px;
   background-color: red;
}

Demo: http://jsfiddle.net/WDth4/

Exactly Center an Image/Div Horizontally and Vertically:

http://css-tricks.com/snippets/css/exactly-center-an-imagediv-horizontally-and-vertically/

Arbaoui Mehdi
  • 754
  • 6
  • 18