问题描述
我试图在同一行显示两个< div>
元素,但在中心。为了集中他们,我不得不设置 margin:auto
;但是,为了得到两个在同一行,我不得不做以下任何一个:
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:
- 设置
display:inline;
(取消居中) - 将
float:left;
(取消居中) - 设置
display:table-cell;
(取消居中)
- Set
display:inline;
(which cancels out the centering) - Set
float:left;
to both (which cancels out the centering) - Set
display:table-cell;
(which cancels out the centering)
我能做什么让 divs
位于中心?或者我应该使用别的东西做这个?我试过< span>
但是inline属性与上面设置 display:inline;
。
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;
.
编辑:这里是< div>
元素的CSS我试图应用这个:
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;
}
在HTML文件中,我只为每个元素添加宽度,我试图添加不同的显示属性,将解决这个问题。
下面建议的包装器想法似乎是唯一的解决方案,但是使用这个CSS也许有一些我做错了?
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?
第二个编辑:一个最后一个添加,什么是最好的方式之间放置这两个< div>
元素之间的空间,因为他们有盒阴影,我不想让他们被压扁
SECOND 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.
推荐答案
您可以这样做,但您需要在外部div上显式宽度。
You can do this, but you'll need an explicit width on your outter div.
尝试此示例:
.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>
希望这有助于!
这篇关于中心< div>并显示在同一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!