Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center <div> and Display on Same Line

Tags:

html

css

I'm trying to display two <div> elements on the same line, but in the center. To center them, I had to set margin:auto; However, in order to get two on the same line, I had to do any one of the following:

  1. Set display:inline; (which cancels out the centering)
  2. Set float:left; to both (which cancels out the centering)
  3. Set display:table-cell; (which cancels out the centering)

What can I do to get both divs to be in the center? Or should I use something else to do this? I've tried <span> but the inline property does the same as stated above for setting display:inline;.

EDIT: Here is the CSS for the <div> elements I'm trying to apply this to:

.homediv {
    background-color:#F7F7F7;
    border:1px solid #FFFFFF;
    -webkit-border-radius:4px;
    -moz-border-radius:4px;
    -o-border-radius:4px;
    border-radius:4px;
    /* width must be defined in the actual element because it can have various sizes */
    -webkit-box-shadow: 0px 0px 8px #888888;
    -moz-box-shadow: 0px 0px 8px #888888;
    box-shadow: 0px 0px 8px #888888;
    margin:auto;
    text-align:center;
    padding:4px;
}

In the HTML file, I only add a width for each element, and now I'm trying to add different display properties that will fix the issue. The "wrapper" idea suggested below seems to be the only solution, but with this CSS maybe there's something I'm doing wrong?

SECOND EDIT: As one final addition, what would be the best way to put space between these two <div> elements, as they have box shadows and I don't want them to be squished together.

like image 415
muttley91 Avatar asked Aug 05 '11 18:08

muttley91


3 Answers

Wrap the two elements in another element. Set display:inline-block; for the inner elements and margin:0 auto; for the outer one.

like image 78
sqwk Avatar answered Sep 21 '22 22:09

sqwk


You can do this, but you'll need an explicit width on your outter div.

Try this example:

.outer {
  width: 200px;
  margin: 0 auto;  
}

.inner1 {
  float: left;
  background-color:
    red; padding: 20px;
}
.inner2 {
  float: left;
  background-color: aqua;
  padding: 20px;
}
<div class="outer">
  <div class="inner1">Hi</div>
  <div class="inner2">Stackoverflow</div>
</div>

Hope this helps!

like image 24
ghayes Avatar answered Sep 20 '22 22:09

ghayes


Have you tried display: inline-block;? An example of the HTML you are working with would help... put one up at http://jsFiddle.net if inline-block doesn't solve your problem.

like image 41
Chris Baker Avatar answered Sep 18 '22 22:09

Chris Baker