Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to center a div without width?

Tags:

html

css

center

hello i would like to know if it is possible to center a div without having a width. because of two different versions of a container depending from language settings with different widths i would like to center it dynamically.

margin: 0 auto;

is not working without any settings of width.

so the structure is simple:

<div id="container">
        <div id="list">
            <span class="up">text large</span>
            <ul class="navigation">
                <li>one</li>
                <li>|</li>
                <li>two</li>
                <li>|</li>
                <li>three</li>
                <li>|</li>
                <li>four</li>
            </ul>
        </div>
</div>

and the css:

.wrapper #container  {
    width: 960px;
    clear: both;
    margin: 0 auto;
}

.wrapper #container #list {
    width: 420px;-->should be dynamically
    margin: 0 auto; --> only works when setting width
}
.wrapper #container #list .up {
    font-size: 11px;
    float: left;
    display: inline-block;
    text-align: right; 
    display: inline;
}
.wrapper .navigation {
    font-size: 10px;
    margin-top: 15px;
    float: left;
    padding-left: 5px;
}
.wrapper .nav li {
    float: left;
    display: inline-block;
    margin-left: 15px;
    list-style: none;
}

so if there is someone who knows how to deal with that i really would appreciate.

thanks alot.

UPDATE:

thanks for answering this question for so far. using:

display: inline-block;

on that container that should be centered works great.

like image 889
bonny Avatar asked Dec 15 '12 21:12

bonny


People also ask

How do I center a div exactly?

To center a div horizontally on a page, simply set the width of the element and the margin property to auto. That way, the div will take up whatever width is specified in the CSS and the browser will ensure the remaining space is split equally between the two margins.

How do I center a div without margins?

use text-align:center for div -> this will align text inside div center. include width property in div (i.e. width:200px) and it will work fine.

How do I center a div according to my screen size?

Easiest way to center something regardless of page width is margin: auto; in your CSS, with height and width defined. Save this answer.

How do I center a div horizontally in my body?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.


1 Answers

Use display: inline-block. See fiddle

.wrapper #container  {
    /* ... */
    text-align: center;
}
.wrapper #container #list {
    display: inline-block;
}
like image 134
ori Avatar answered Oct 07 '22 13:10

ori