user3076755
user3076755

Reputation: 5

HTML/CSS - Horizontally center a div that is constantly changing in width

I have a parent div (for sake of test we'll call it #parent) and a child div (test reasons #child). #parent is absolutely positioned to the bottom of the page, with a fixed width of 100% and a height of 75px.

child is a div that holds dynamic content (being changed with jQuery). Seeing as it is dynamic, the width of the div is always different. What is the most efficient way to center this div horizontally, since the width is always unknown & different? Any help would be awesome.

Upvotes: 0

Views: 140

Answers (5)

Breezer
Breezer

Reputation: 10490

Make it display as an inline element and give the parent the property of text-align center problem solved

#parent{
text-align:center;
}
#child{
display:inline-block;
}

Edit:

check how it works http://jsfiddle.net/ECMau/1/

Upvotes: 0

Ishan Jain
Ishan Jain

Reputation: 8161

Centering a div using CSS:

HTML:

   <div class="center">    
        .... more content ....
    </div>

CSS:

  .center {
       margin: 0 auto;
    }

OR

 .center {
       margin-left: auto;
       margin-right: auto;
    }

The margin: 0 auto; sets the left and right margin to whatever pixel left on the left and right of the page.

Try in jsfiddle

Upvotes: 0

Code Maverick
Code Maverick

Reputation: 20415

For fun you could use the CSS Flexible Box Layout Module. Here is a jsFiddle demonstrating what you could do:

See working jsFiddle demo


HTML

<footer>
    <div class="dynamic-content">Here is some child dynamic content</div>
</footer>


CSS

body 
{
    background: #ccc;
}
footer 
{
    /*  As of August 2012, only supported in Chrome 21+ */
    display: -webkit-flex;
    display: flex;
    
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    
    background: #232323;
}
footer .dynamic-content 
{
    flex: 1;
    
    padding: 10px;
    margin: 0 auto;
    
    background: #545454;
    color: white;
    font-family: verdana;
}

Upvotes: 0

Matthew
Matthew

Reputation: 2290

The correct way to do this would be the following:

#child {
    margin: 0 auto;
}

This sets the top/bottom margins to 0, and then the left/right margins to auto - which means "as large as possible". So you have two equal margins on the left and the right, filling up the space completely, and hence you have a centred div.

This will only work on block elements like divs though - inline elements cannot have auto margins. If you need to centre an inline element (like a span or some text), use text-align: center; on the parent:

#parent {
    text-align: center;
}

Upvotes: 2

James Dorfman
James Dorfman

Reputation: 1818

You could set the margins to: margin: 0, auto;

Upvotes: 1

Related Questions