Fixed div does not go beyond the screen's righ

2019-06-09 07:22发布

问题:

I have a div which has a fixed position. The problem is when the div moves to the right it does not go beyond the screen's right edge. It resizes itself making its width smaller. This does not happen when I give it a fixed width. But I want it to have a fluid width with max-width defined. I do not want it to stick to the right edge by defining right. I want to define the left position and let the excess go out of the screen.

You can see the problem here: http://codepen.io/anon/pen/BjZppJ

Click on the div in the example to see the problem.

HTML CODE

<div> -- RANDOM TEXT HERE -- </div>

CSS CODE

div
{
  position: fixed;
  left: 0;
  top: 0;
  padding: 20px;
  max-width: 500px;
  background: rgba(112,66,102, .1);
}

div.right
{
  left: calc(100% - 300px)
}

回答1:

Add width: 100%; to the div, by doing so it will always try to be 100% the width of it's parent, but since you set the max width, it will not quite get there.

$('div').click(function(){
  
  if($(this).hasClass('right'))
  {
    $(this).removeClass('right')
  }
  else
  {
    $(this).addClass('right')
  }
     
  
})
div
{
  position: fixed;
  left: 0;
  top: 0;
  padding: 20px;
  max-width: 500px;
	background: rgba(112,66,102, .1);
  width: 100%;
}

div.right
{
  left: calc(100% - 300px)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>as dfas dfa sdf asdfasd fsdf sdfasdfa sdfasdfasd fasdfa sdfa sdfasdfa sdfasdfa sdfsdf sd</div>



回答2:

adding width:100% to the style definitions of the div will do the trick.

Default is width:auto and for elements with fixed positions it will try to calculate a width which does not overflow the window dimensions.