Making a website. It consists of one main container in the center and a sidebar. I only know how to make the sidebar be on the far left or right of the screen. What I want to do though is make the sidebar stick to the left of my main container. Is there a way of doing this?
The sidebar is just a flexbox with a few links and images in it.
#container {
background-color: deepskyblue;
width: 500px;
margin: auto;
padding: 100px;
}
#sidebar {
background-color: red;
width: 200px;
padding: 10px
}
<div id="sidebar" style="float: left">
<p>Sidebar</p>
</div>
<div id="container">
<p>Container</p>
</div>
I tried using float:left
but that just makes the sidebar go to the very edge of the page. What I need is the sidebar to sort of stick to the container.
4
Answers
enter code here
If you want the container to be centered then you can use css grid to create 3 columns. We make the two side columns
1fr
so they’re equal width then the middle column to befit-content
. We can then usealign-self
to push the side bar to the edge of the container. CSS tricks has a great primer on grid and Kevin Powell has a useful video on youtubeExample below:
You can do this in multiple steps:
First, to position the sidebar in the top left of the container, we can make the
#container
‘s positionrelative
so that other things can beabsolute
ly positioned relative to it, then we can position the#sidebar
absolute
ly in the top left.Next, we can move the sidebar to the left equal to it’s width:
Use flexbox layout since it is versatile enough for most cases. Add a third column that has same proportions as the first one; that way all three columns will be sized and centered properly. The following example uses a pseudo element as the third column: