Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you dynamically center a div inside another div element relative to content?

I am currently trying to specifically position multiple divs, inside of another div, which is itself centered in another div.

To get a visual perspective of what I'm trying to do:

enter image description here

I have a parent div with a specific height and width. Inside of that div element should be another div (white border), which is centered. Again, inside of that div should be a number of specifically positioned (green) divs. The green divs should be created and appended by a javascript function.

I now want the centered divs' height and width dynamically change, when I put my green divs inside.

My current code is:

HTML:

<div id="grandparent">
    <div id="parent">
        <!-- <div class="child"></div> -->
        <!-- <div class="child"></div> -->
        <!-- <div class="child"></div> -->
        <!-- <div class="child"></div> --> (commented because they're not yet in there)
    </div>
</div>

CSS:

#grandparent{
    height: 130px;
    width: 145px;
    background-color: #000000;
    border: 3px solid #00ffff;
    display: table;
}

#parent{
    display: table-cell;
    vertical-align: middle;
}

.child{
    height: 23px;
    width: 23px;
    float: left;
}

javascript:

for(var i = 0; i < number; i++){
    var top = ...
    var left = ...
    var child = $("<div class='child'></div>");
    child.css("top", top);
    child.css("left", left);
    $("#parent").append(child)
}

So far my content was based on this guide: http://www.vanseodesign.com/css/vertical-centering/

How can a div's size change according to its content? Will a div then stay centered, if you change this content?

like image 646
Joliver Avatar asked Oct 02 '22 00:10

Joliver


1 Answers

If I understand you don't need any JS to center the divs inside just use inline-block:

#parent{
  display: table-cell;
  vertical-align: middle;
  text-align:center; /*Add this*/
}

.child{
  height: 23px;
  width: 23px;
  /*float: left; Remove this*/
  display:inline-block; /*Add this*/
}

EDIT

Based on your picture you may need an extra div:

 <div id="grandparent">
  <div id="parent">
   <div class="border">
     <div class="child"></div>
        ....

Check the full demo http://jsfiddle.net/R9YGb/10/

like image 80
DaniP Avatar answered Oct 13 '22 10:10

DaniP