1

I have been searching on google and stack overflow for a while, but nothing seems to work.

I am trying to center a div within a div, which is all contained within a page wrapper. I can get it to center horizontally, but not vertically. Any suggestions?

I have tried display:inline-block with vertical-align:middle, but it had no effect.

CSS

html {
  margin: 0;
  padding: 0;
}

body {
  margin: 0;
  padding: 0;
  background-color: black;
}

#page-wrapper {
  padding: 0 12.5% 0 12.5%;
  margin: 0;
}

#outer {
  width: 100%;
  height: 1000px;
  background-color: darkgray;
  position: relative;
}

#inner {
  position: relative;
  width: 50%;
  height: 20%;
  margin: 0 auto;
  background: grey;
}
<body>
  <div id="page-wrapper">
    <div id="outer">
      <div id="inner"></div>
    </div>
  </div>
</body>
Dhaval Jardosh
  • 7,151
  • 5
  • 27
  • 69
karafar
  • 496
  • 4
  • 14
  • Are you OK with using `display: flex`? – Alberto Rivera Nov 21 '17 at 00:02
  • 1
    Possible duplicate of [How to vertically center a div for all browsers?](https://stackoverflow.com/questions/396145/how-to-vertically-center-a-div-for-all-browsers) (There are dozens of duplicates of this question. If "nothing seems to work" with the many answers already available, please be clearer about what specifically is different about your situation.) – Daniel Beck Nov 21 '17 at 00:04

3 Answers3

2

You could:

A. Change the height to be a specific number and add margin-top: -height;

OR

B. Add this into the code for the #inner

position:absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Example of B: CodePen.io

OR

C. If you want to make it fancy use a flexbox (instructions here: Flexbox complete guide) and add:

display: flex; justify-content: center; align-items: center;

Hello World
  • 35
  • 11
1

This may help https://css-tricks.com/centering-css-complete-guide/

change

#inner {
  position:relative;
  width: 50%;
  height: 20%;
  margin: 0 auto;
  background:grey;
}

to

#inner {
  width: 50%;
  height: 20%;
  margin: 0 auto;
  background:grey;

  /* magic here */
  position:absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Daniel Garcia
  • 462
  • 3
  • 8
0

You can do that by using flexbox, together with align-items: center; and justify-content: center;

Have a look at this: https://codepen.io/anon/pen/GOQwre

DunDev
  • 210
  • 2
  • 13