Fixed div does not go beyond the screen's right edge

*爱你&永不变心* 提交于 2019-12-10 12:15:39

问题


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.



来源:https://stackoverflow.com/questions/34724803/fixed-div-does-not-go-beyond-the-screens-right-edge

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!