0

I have the following code. Initially there will be a header division whose width will be set to 100%. But when a add some new absolute div , that is positioned outside the full width of the screen , ( so that horizontal scroll is enabled ) , the width of the header will not be 100% ( as new space has been added )

Please take a look at the following code , where i have simulated the problem.

I would like to have the width of the header as same as the screen , independent of how much portion i am seeing. I tried using vw instead of % but did not work out.

Is there a way to do it in css itself ?

Or do i need to dynamically change the width each time using jquery ?

$(document).ready(function() {

  $("#btn").click(function() {


    $("#sample").toggle().css({
      top: 100,
      right: -110
    })
  });
})
body {
  margin: 0;
  padding: 0;
}
#header {
  width: 100%;
  height: 100px;
  background: #ccc;
}
#sample {
  width: 300px;
  height: 200px;
  background: #444;
  display: none;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
</div>

<div id="sample">
</div>

<button id="btn">Click here</button>
Sooraj
  • 7,875
  • 7
  • 58
  • 91

2 Answers2

1

A little addition to the JS. It keeps the header position: static (unfixed) because there are no changes to the orig css.

$(function(){
  $("#btn").click(function() {
    $("#sample").toggle().css({
      top: 100,
      right: -110
    })
    var clicks = $(this).data("clicks")
    var w = $("#header").width()
    if(clicks){ 
      $("#header").css("width", w - 110)

    }else{
      $("#header").css("width", w + 110)

    }
    $(this).data("clicks", !clicks);

  });
})
body {
  margin: 0;
  padding: 0;
}
#header {
  width: 100%;
  height: 100px;
  background: #ccc;
}
#sample {
  width: 300px;
  height: 200px;
  background: #444;
  display: none;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="myClass">This is clickable</div>
<div id="header">
</div>

<div id="sample">
</div>

<button id="btn">Click here</button>

Info about the use of data for toggling clicks

Community
  • 1
  • 1
jack blank
  • 4,745
  • 7
  • 38
  • 66
1

$(document).ready(function() {

  $("#btn").click(function() {


    $("#sample").toggle().css({
      top: 100,
      right: -110
    })
  });
})
body {
  margin: 0;
  padding: 0;
  padding-top: 100px;
}
#header {
  width: 100%;
  height: 100px;
  background: #ccc;
  position: fixed;
  top: 0px;
}
#sample {
  width: 300px;
  height: 200px;
  background: #444;
  display: none;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">
</div>

<div id="sample">
</div>

<button id="btn">Click here</button>
Abhinav
  • 156
  • 2