Search code examples
htmlcsspositioningcss-positionscreen-size

How can I make a div with "position:fixed" to stay out of the screen if the window overflows?


I have two divs as in the illustration below. The position of div #2 is fixed, so it sticks to the right side of the screen no matter how small it might be. If the screen is small, then the div #2 starts to overlap over div #1, which I do not want. I know that this problem is being caused because the left and right positions of both divs are in percentages, but they must stay in percentages only. I can work around this problem using Javascript, but I was thinking of a pure CSS solution for the users who may have Javascript disabled.

+---------+ +---------+
|         | |         |
|         | |         |
|   #1    | |    #2   |
|         | |         |
|         | |         |
+---------+ +---------+

What's happening if the screen is small:

+------ +---------+
|       |         |
|       |         |
|   #1  |    #2   |
|       |         |
|       |         |
+------ +---------+
-------scrollbar---

What should happen (screen ends where the scrollbar ends):

+---------+ +------
|         | |      
|         | |      
|   #1    | |    #2
|         | |      
|         | |      
+---------+ +------
------scrollbar----

Solution

  • Use margin to position your div #2 rather than position: fixed.