2 div in another "container" div - 自适应宽度

2 div in an other "container" div - Adapt width

我的 css 有问题。我在容器 div "container" 中有 2 div "left" 和 "main"。我的容器宽度是主体宽度的 90℅,并且有边距:%3 auto(使容器居中)。

.container{
margin:3% auto;
width:90%;}

现在,我想在我的容器中加入一些特别的东西:我的 "left" 宽度 = 容器的 20%,在这个“左边 div” 右边留出一个边距来分隔 "left"和 "main"

#left {
display:inline-block;
padding:10px;
background-color:#32CD32;
vertical-align:top;
list-style:none;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
border:solid 2px black;
/*width:????? HERE I WANT AN ADAPTABLE WIDTH TAKING 20% OF THE CONTAINER WIDTH*/}

而我的 main 的宽度必须占用容器的其余宽度。

#main {
background-color:#32CD32;
vertical-align:top;
display:inline-block;
padding:10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
border:solid 2px black;
text-align:center;
/*width:80%; HERE, I WANT AN ADAPTABLE WIDTH TAKING THE REST OF THE CONTAINER*/}

但是当我使用 % 作为主要宽度和左侧宽度时,它占用主体 ℅。而且,我不知道怎么说“占用容器的其余宽度。

<div class="container">
<div id="left">
<li>LIST1</li>
<li>LIST2 </li>
<li>LIST3 </li></div>
<div id="main">
    <div id="new_comment"class="eblock">new comment</div>
    <div id="comments"class="eblock">
    <div id="onecomment"> new comment </div>
    <div id="onecomment"> new comment </div>
    <div id="onecomment"> new comment </div>
    <div id="onecomment"> new comment </div>
    <div id="onecomment"> new comment </div>
    </div>
</div>
</div>

感谢您的帮助。

您遇到的问题来自于 CSS 所做的称为框尺寸调整的事情。这告诉浏览器如何布置您的框(例如您的 div 元素)。

现代浏览器使用的默认框大小称为 padding-box。它计算框的宽度(在您的示例中为 #container 的 20% 或 80%),然后将填充和边框添加到计算出的宽度。这意味着您的元素最终占用的空间比您最初预期的要多 space。

一种可能的解决方案是覆盖默认的框大小。设置 box-sizing: border-box 告诉浏览器在计算宽度时包括填充和边框,即这些值包含在容器宽度的 20% 中。很多人建议只在所有元素上设置此选项(请参阅有关该主题的 Paul Irish's article)。

对于你的情况,我建议设置:

#left {
    width: 20%;
    margin-right: 5%;
}

#main {
    width: 75%;
}

现在,在某些情况下,浏览器必须对值进行舍入。因此,您最终可能会得到总计超过可用值 space 的值。如果发生这种情况,只需调整一些百分比(例如设置 margin-right: 4%)。

给你

Working jsfiddle

.container {
    width:90%;
    height:200px;
    border:1px solid;
}

.left {
    width:auto;
    height:200px;
    background:red;
    overflow:hidden;

 }

.main {
    height:200px;
    width:60%;
    background:blue;
    float:left;
    margin-right: 10px;
 }

灵感来自