Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

html - Center <div> and Display on Same Line

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...