2010-09-14 113 views
7

我想知道如果你能帮我定位两个div,mainContent和sideContent彼此相邻吗?CSS定位元素彼此相邻

HTML:

<div id='main'> 
    <div id='mainContent'> 
    </div> 
    <div id='sideContent'> 
    </div> 
</div> 

CSS: #

#main { width: 100%; min-height: 400px; 
    background: #0A3D79; /* for non-css3 browsers */ 
    background: -webkit-gradient(linear, left top, left bottom, from(rgb(20,114,199)), to(rgb(11,61,122))); /* for webkit browsers */ 
    background: -moz-linear-gradient(top, rgb(20,114,199), rgb(11,61,122));} /* for firefox 3.6+ */ 
    /*gradient code from http://www.webdesignerwall.com/tutorials/cross-browser-css-gradient*/ 

    #mainContent { width: 75%; margin-top: 20px; padding-bottom: 10px; min-height: 400px; background-color: blue; } 
    #sideContent { width: 22%; margin-top: 20px; padding-bottom: 10px; min-height: 400px; background-color: red; border-style: solid; border-left-width: 3px; border-left-color: white;border-right-width:0px;border-top-width:0px;border-bottom-width:0px;} 

我包括所有的CSS,因为我不知道究竟会对这种东西的效果。此外,我试图让sideContent和mainContent内联显示,但它们似乎消失了。任何想法为什么?

回答

10

如果你想要它们并排显示,为什么sideContent是mainContent的子节点?让他们的兄弟姐妹然后使用:

float:left; display:inline; width: 49%; 

在他们两人。

#mainContent, #sideContent {float:left; display:inline; width: 49%;} 
+0

我的错误,在我他们是兄弟姐妹。我已经阅读并编辑了原文,很快就会尝试您的实施。谢谢! – djs22 2010-09-14 03:05:21

+0

不用担心! :) – sheeks06 2010-09-14 03:15:42

+0

完美工作,但由于某种原因,我不再继承背景。谢谢您的帮助!我要去探索这个问题....任何建议都会很棒! – djs22 2010-09-14 03:17:00

0

如果你不知道有多少元素将被使用,或者希望他们有正常宽度,唯一的方法是使用一个表:

<div id='main'> <table> <tbody> 
    <tr> 
    <td><div id='mainContent'></div></td> 
    <td><div id='sideContent'></div></td> 
    </tr> 
</tbody> </table> </div> 
+0

'

'元素从来不需要布局。表布局规则可以应用于任何使用'display:table-cell'和'display:table-row'的元素。还有Flexbox('display:flex')和CSS Grid Positioning('display:grid')。 – Dai2017-03-13 23:19:21