The Problem
Ignore the image for a second... .img-responsive
just makes the image take up 100% of the available space in the parent container.
Then the question becomes, can I add position: fixed
to a div and still have it take up the same width as it's parent which has .col-xs-3
(width: 25%
)? Once we resolve that, the image should fall into line.
As you may already know about fixed positioning:
for a fixed positioned box, the containing block is established by the viewport
###Meaning Fixed is always relative to the parent window, never an element.
Simple Solution
If the viewport is the same width as the parent div, this can be resolved trivially:
HTML:
<!-- language: lang-html -->
<div class="row">
<div class="col-xs-9" id="content">C</div>
<div class="col-xs-3">
<div id="navbar">Navbar</div>
</div>
</div>
Relative
- div takes up 100% of width of parent (.col-xs-3
):
<!-- language: lang-css -->
#navbar {
background: yellow;
position: relative;
}
Fixed
- div takes up 100% of screen - apply .col-xs-3
width ourselves:
<!-- language: lang-css -->
#navbar {
background: yellow;
position: fixed;
width: 25%;
}
###Demo in Fiddle
[]
fiddle demo fixed vs relative
Better Solution
However, that solution isn't much help to us because the the .container
class applies variable widths at different breakpoints to the row. This causes 25% of the parent div and 25% of the viewport to get out of sync.
So how can we get them to sync up again?
To answer that, let's look at exactly what .container is doing:
<!-- language: lang-css -->
.container {
@media (min-width: @screen-sm-min) {
width: @container-sm;
}
@media (min-width: @screen-md-min) {
width: @container-md;
}
@media (min-width: @screen-lg-min) {
width: @container-lg;
}
}
So instead of trivially being able to apply a 25%
width, we now have to mimic the width applied by .container. Here's how:
Here's some sample markup:
<!-- language: lang-html -->
<div class="container">
<div class="row">
<div class="col-xs-8 content">Content</div>
<div class="col-xs-3 col-xs-offset-1" id="sidebar-outer">
<div id="sidebar">
Width: <span id="width-placeholder"></span>px
</div>
</div>
</div>
</div>
Now we can apply a width at all breakpoints with the following CSS:
<!-- language: lang-css -->
#sidebar {
background: yellow;
position: fixed;
width: 25%;
}
@media (min-width: 768px) {
#sidebar {
width: 158px; /* 632 * .25 */
}
}
@media (min-width: 992px) {
#sidebar {
width: 213px; /* 852 * .25 */
}
}
@media (min-width: 1200px) {
#sidebar {
width: 263px; /* 1052 * .25 */
}
}
Here's a side by side comparison of using relative vs fixed position with styling:
##Demo in Fiddle
[]
fiddle demo container
Back to our problem at hand:
Just take the demo from above and add back in our responsive image:
#Solution Demo in Fiddle
As a note: most sites opt to use a fixed width side navbar when using position:fixed
in order to sidestep these kinds of issues.