Michael Michael - 5 months ago 45
Javascript Question

Bootstrap Navbar (affixed) Dynamic Width

I am having an issue getting an affixed bootstrap navbar to adjust it's width properly when the page is scrolled.

I would either like the navbar to maintain the width inside of its containing element when the page scrolls OR take the full width of the page (starting from left to right)

what am I doing wrong, or what do I need to do?

Fiddle: https://jsfiddle.net/btckkdkk/12/

<div class="container">
<div id="renderbody">
<div id="renderbody-inner">
<nav class="navbar navbar-default" role="navigation" data-spy="affix" data-offset-top="100" style="margin-bottom:5px">
<div class="col-sm-12">
<button type="button" class="navbar-toggle navbar-toggle-sm navbar-left" data-toggle="collapse" data-target="#storysubmit-navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<form action="#" class="navbar-form navbar-form-custom navbar-left" role="search" id="searchForm" data-results-target="#storyList">

<div class="input-group">
<input type="text" class="form-control input-sm" placeholder="Search" name="searchTerms" id="searchTerms" />
<div class="input-group-btn">
<div class="btn-group">
<button type="submit" class="btn btn-sm btn-default"><i class="glyphicon glyphicon-search"></i></button>
</div>
<a href="#" class="btn btn-sm btn-link" style="margin-right:30px">Advanced</a>
</div>
</div>
</form>
<div class="navbar-form navbar-right collapse navbar-collapse" style="padding-right: 15px; padding-left: 15px; margin-right:0" id="storysubmit-navbar">
<a href="#" class="btn btn-default btn-sm">
<i class="glyphicon glyphicon-pencil margin-right-5" aria-hidden="true"></i>
Submit
</a>
</div>
</div>

</nav>
<div style="height:500px; background-color:darkgray;">
</div>
<div style="height:500px; background-color:lightgray;">
</div>
<div style="height:500px; background-color:darkgray;">
</div>
<div style="height:500px; background-color:lightgray;">
</div>
</div>
</div>
</div>

Answer

The .navbar.affix uses fixed position. You can to use special properties:

For absolutely positioned elements (those with position: absolute or position: fixed), it specifies the distance between the margin edge of the element and the edge of its containing block.

For relatively positioned elements (those with position: relative), it specifies the amount the element is moved below its normal position.

I have two solutions.

1) I've added this CSS to your https://jsfiddle.net/btckkdkk/8/:

.navbar.affix {
    left: 0;
    width: 100%;
}

Check the result: https://jsfiddle.net/glebkema/essb11a1/

2) But I prefer this fix:

.navbar.affix {
    left: 0;
    right: 0;
    width: auto;
}

Please check too: https://jsfiddle.net/glebkema/essb11a1/3/