Giorgio
Giorgio

Reputation: 1970

Display div as centered blocks without 100% width

I know it's a super-basic question, but I'm not able to find a solution. I have 2 div and I would like to display them as blocks (one below the other) without having 100% width. Here's my code.

HTML

<div id="container">
    <div class="test">one</div>
    <div class="test">two</div>
</div>

CSS

.test {
    display:inline-block;
    clear: both;
    border:1px solid;
}

#container {
    clear:both;
    text-align:center;
}

Unfortunately this answer doesn't fit to me, since I need to center blocks horizontally (so float cannot be applied in my case). Here's the fiddle. Thanks in advance.

Upvotes: 0

Views: 2722

Answers (4)

Ayaz Shah
Ayaz Shah

Reputation: 435

display:inline-block; is not allow the second line. Therefore I removed it and define width for both div test one two you can resize it and margin:auto is align center the both div in container here is an example

Upvotes: 0

G-Cyrillus
G-Cyrillus

Reputation: 106058

to center them on top of each other without taking 100% width and still use margin:auto; use : display:table;

.test {
display:table;
margin:auto;
border:solid;/* to see it */
}

Upvotes: 4

dkasipovic
dkasipovic

Reputation: 6130

You can also center the div by adding 50% left offset, and then negative margin in amount to half width of the div. I do not know how much is this applicable to your case, but here is an example:

.test {
    position: relative;
    border:1px solid;
    width: 300px;
    left: 50%;
    margin-left: -150px;
}

You can see it in action here: http://jsfiddle.net/b8LuQ/7/

Upvotes: 0

thosetinydreams
thosetinydreams

Reputation: 1000

You can specify the width of the divs, change display to block, and use margin: 0 auto to center them.

JSFiddle

Upvotes: 1

Related Questions