Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center small div in big div vertically and horizontally

My code is as follows:

<div id="bigDiv">
  <div id="smallDiv">DD</div>
</div>

My CSS is as follows:

#bigDiv {
  border: 1px solid red;
  height: 300px;
  width: 300px;
  vertical-align: middle;

}

#smallDiv {
  border: 1px solid black;
  height: 100px;
  width: 100px;
  margin: 0 auto;
}

I want to center the small div vertically and horizontally inside the big div. The horizontal works, but the vertical doesn't.

http://jsfiddle.net/4Gjxk/

like image 811
user974896 Avatar asked Jan 11 '13 15:01

user974896


People also ask

How do you center align a div both horizontally and vertically?

You can do this by setting the display property to "flex." Then define the align-items and justify-content property to “center.” This will tell the browser to center the flex item (the div within the div) vertically and horizontally.

How do I vertically center a div in another div?

Vertically centering div items inside another div Just set the container to display:table and then the inner items to display:table-cell . Set a height on the container, and then set vertical-align:middle on the inner items. This has broad compatibility back as far as the days of IE9.

How do I center a div horizontally in a div?

To Horizontally centered the <div> element: We can use the property of margin set to auto i.e margin: auto;. The <div> element takes up its specified width and divides equally the remaining space by the left and right margins.

Does vertical align work with div?

The CSS vertical align property works smoothly with tables, but not with divs or any other elements. When you use it in a div, it aligns the element alongside the other divs and not the content — which is what we usually want). This only works with display: inline-block; .


2 Answers

Read this: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

If you cannot be bothered reading do this:

    #bigDiv {

      position: relative; /* Needed for position: absolute to be related to this element and not body */

      border: 1px solid red;
      height: 300px;
      width: 300px;
      vertical-align: middle;
    }

And change the other to:

#smallDiv {
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;

  border: 1px solid black;
  height: 100px;
  width: 100px;

}

Here is the updated jsfiddle: http://jsfiddle.net/4Gjxk/1/

like image 193
tsujp Avatar answered Nov 13 '22 02:11

tsujp


I believe this is the most straight-forward solution with the least amount of CSS. Since 100 / 300 = ~.33 you can use a 33% margin like so:

#bigDiv {
  border: 1px solid red;
  height: 300px;
  width: 300px;
}

#smallDiv {
  border: 1px solid black;
  height: 100px;
  width: 100px;
  margin: 33%;
}

Here's the updated jsFiddle.

like image 34
jonathan.cone Avatar answered Nov 13 '22 02:11

jonathan.cone