我想在页面上有两个浮动div,它们的组合宽度填充浏览器窗口的整个宽度。我希望一个div具有15em的固定宽度并显示在左侧。我将这称为侧边栏div。我希望另一个div动态地使用剩余的可用宽度,并显示在右侧。我将此称为主要内容div。
我希望主内容div的宽度填充侧边栏div未使用的所有可用宽度,即使主内容div中的所有内容都不需要所有可用宽度,我希望这种情况发生
为了使事情更复杂,我希望主要内容div在侧边栏div之前编码,但我希望侧边栏div显示在右侧主要内容div之前的左侧。这个复杂性使我的问题与我在其他用户中找到的其他类似问题不同。
除了在没有内容需要主内容div的完整可用宽度的页面上,我拥有一切正常运行的功能。例如,如果我在p中有一行文本包装到下一行,因为它比可用宽度长,所以一切都按照需要运行。当ap中的文本行不足以利用主内容div可用的全部宽度时,主内容div仅与其内容所需的宽度相同,并且在页面右侧挂起,留下大的内容侧边栏和主要内容div之间的空白区域。
.right-main-content {
float: right;
text-align: left;
margin-left: 16em;
padding: 0;
background: red
}
.left-sidebar {
float: left;
text-align: left;
width: 15em;
margin-right: -15.5em;
background: green
}

<body>
<div class="right-main-content">
<p>
This is the right main content div.
</p>
<p>
</div>
<div class="left-sidebar">
<p>this is the left sidebar div</p>
<p>with a fixed width of 15em</p>
</div>
</body>
&#13;
答案 0 :(得分:1)
我建议使用父级width
的计算驱动100%
,减去左侧边栏的15em
宽度。这可以通过使用 calc() :
.right-main-content {
float: right;
width: calc(100% - 15em);
background: red;
}
.left-sidebar {
float: left;
width: 15em;
background: green;
}
&#13;
<body>
<div class="right-main-content">
<p>
This is the right main content div.
</p>
<p>
</div>
<div class="left-sidebar">
<p>this is the left sidebar div</p>
<p>with a fixed width of 15em</p>
</div>
</body>
&#13;
这样,您只需要指定两个width
和float
属性。
另请注意,您不需要text-align: left
,因为它默认为左对齐。
希望这有帮助! :)
答案 1 :(得分:0)
您可以在css和Viewport Sized Typography中使用calc
来设置右侧div的宽度。
按照你的例子试试这个:
.left-sidebar {
width:15em;
float:left;
}
.right-main-content {
width:calc(100vw - 16em);
float:right;
}
这是我创建的一个例子。 https://codepen.io/florinsimion/pen/eEYoeX
答案 2 :(得分:0)
您可以尝试仅浮动div.left-sidebar
,并使div.right-main-content
的边距值与div.left-sidebar
宽度相同,如下所示:
.right-main-content {
text-align: left;
margin-left: 15em;
padding: 0;
background: red;
width:100%;
}
.left-sidebar {
float: left;
text-align: left;
width: 15em;
background: green
}