Reputation:
I have two div
s formatted as panels. One is the main panel whereas the other is something like a sidebar. I would like the sidebar to float to the left, but the latter is embedded inside the main div
. I want it to display next to the main panel, rather than inside it.
I know I could float the sidebar left, the main panel right and add some more content after them and use clear: both
to make the page resize and scroll properly; this sounds like a hack, however, and it requires specifying the size of both panels. If I could float just the sidebar to the left, then the main panel would size itself automatically to cover the rest of the page.
My HTML code at the moment looks something like this:
<div id="sidebar" class="panel">
Sidebar
</div>
<div id="content" class="panel">
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>
And the CSS of interest is:
#sidebar {
float: left;
width: 30%;
}
In the screenshot below, one can easily see that the sidebar is floating to the left, but is somehow inside the main panel. In the HTML code, however, the sidebar is clearly outside the main panel. How can I fix that without having to use float: right
on the main panel?
Upvotes: 3
Views: 3518
Reputation: 513
@Angelos you could use the old table layout so the left part has a fixed width and the right part takes up all the rest available space..
Upvotes: 0
Reputation: 7682
* {
box-sizing: border-box;
}
#sidebar {
width: 30%;
float: left;
border: 1px solid black;
}
#content {
float: right;
width: 70%;
border: 1px dashed blue;
}
.clearfix:after,.clearfix:before {
display: table;
content: '';
clear: both;
}
<div class="clearfix">
<div id="sidebar" class="panel">
Sidebar
</div>
<div id="content" class="panel">
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>
</div>
If you want use floats - you should use float for both blocks, because float "creates own flow", that's why you got overlaying.
But I'd rather recommend you using flexboxes as it was mentioned before, because it's quite powerful technology which is widely supported. According to this site https://caniuse.com/#search=flexbox using flexbox is supported by 96.63% devices all over the world.
Upvotes: 1
Reputation: 42352
If flexbox
is an option, you can can make the main panel cover the rest of the horizontal space:
Specify display: flex
on the wrapper element (body
in the demo below)
Add flex: 1
to the main panel so that if grows to fit the remaining space available.
See simplified demo below:
body {
display: flex;
}
.panel {
border: 1px solid;
}
#sidebar {
width: 30%;
}
#content {
flex: 1;
}
<div id="sidebar" class="panel">
Sidebar
</div>
<div id="content" class="panel">
<p>Content</p>
<p>Content</p>
<p>Content</p>
</div>
Upvotes: 3