1

I have three div as shown below. I want to keep inner div in exactly center of outer div. I found some solution with position style set, but it was creating problem with my other element in my project, so I don't want to use position in style. I want to center inner div without using position style.

<div id="container">
    <div id="outer">
        <div id="inner"></div>
    </div>
</div>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
shyam_
  • 2,370
  • 1
  • 27
  • 50

3 Answers3

2

You can use CSS flexbox.

#outer {
    display: flex; /* establish flex container */
    justify-content: center; /* center #inner horizontally */
    align-items: center; /* center #inner vertically */
}

Note that flexbox is supported by all major browsers, except IE 8 & 9. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add all the prefixes you need, post your CSS in the left panel here: Autoprefixer.

DEMO

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
  • thanks..your solution did work. just updated fiddle link for others http://jsfiddle.net/shyam_bhiogade/r26vc8t6/ – shyam_ Nov 25 '15 at 05:09
  • hi michael, i have also updated another solution..do you see any issue in that. thanks – shyam_ Nov 25 '15 at 05:19
  • No issues with tables. That's another way to center things. I prefer flexbox because it's responsive, flexible and specifically designed for layouts. – Michael Benjamin Nov 25 '15 at 05:24
  • hey michael, the solution i gave also works.can you please upvote it. – shyam_ Nov 25 '15 at 23:23
  • @shyam_, if it works I will upvote. But I tested it before and it didn't work. And the demo uses different code than posted in the answer: Your answer uses table properties, but your demo uses flexbox. Please update your answer and post a working demo so I can upvote. – Michael Benjamin Nov 25 '15 at 23:27
2

found another solution

#outer {
    display: table-cell;
    vertical-align: middle;
}
#inner {
    margin:auto;
}

http://jsfiddle.net/dspLofov/1/

shyam_
  • 2,370
  • 1
  • 27
  • 50
1

Here is how I would center a div inside a div, the css is as follows

#outer {

    background: green;
    height: 200px;
    width: 200px;
    position: relative;
}

#inner {
    position: absolute;
    top: 50%;
    bottom: 50%;
    left: 50%;
    width: 50%;
    height: 50%;
    overflow: auto;
    background: red;
    transform: translate(-50%, -50%);
    resize: both;
    padding: 1em;
}
//I put color in the background so it is easy to see.

here is the fiddle: https://jsfiddle.net/dwillhite/464Lf6wr/embedded/result/

Hope this helps!

David Willhite
  • 115
  • 1
  • 4