【问题标题】:2 div in an other "container" div - Adapt width另一个“容器” div 中的 2 个 div - 调整宽度
【发布时间】:2016-03-02 00:37:00
【问题描述】:

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

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

现在,我想在我的容器中添加一些特别的东西:我的“左”宽度 = 容器的 20%,在这个“左 div”上的右边距以分隔“左”和“主”

#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 {
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>

感谢您的帮助。

【问题讨论】:

  • 如果您有新问题,请发布新帖子,而不是编辑现有问题。如果您进行编辑,则所有给出的答案都将无效。

标签: html css width


【解决方案1】:

给你

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;
 }

灵感来自https://stackoverflow.com/a/1767270/5999686

【讨论】:

  • 谢谢,我修改了我的代码并且它工作了,但是由于这次更新,我遇到了另一个问题:/(我编辑了帖子)
【解决方案2】:

您遇到的问题来自 CSS 所做的称为框大小调整的事情。这告诉浏览器如何布局你的盒子(例如你的 div 元素)。

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

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

在你的情况下,我建议设置:

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

#main {
    width: 75%;
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2011-09-03
    相关资源
    最近更新 更多