Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: How to fix an element horizontally but not vertically?

You can see an example here: http://alboard.free.fr/adrien/test.html

The layout is based on horizontal scrolling (the red element). But I want the top part to be fixed (the blue element).

If the user resizes the viewport, a vertical scrollbar will appear. If at this point the user scrolls down, the red element will go up while the blue element will remain fixed. This breaks the layout (the red element overlaps with the blue element).

Is it possible to make the blue element fixed horizontally but scrollable vertically?

I know there are javascript solutions based on onscroll. But there's always a latency between the moment the user scrolls and the moment the element's position adapts to the new offset.

like image 435
pangel Avatar asked Sep 25 '09 18:09

pangel


People also ask

How do I place an element horizontally in CSS?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

How can we center horizontally as well as vertically any item inside an element?

For vertical alignment, set the parent element's width / height to 100% and add display: table . Then for the child element, change the display to table-cell and add vertical-align: middle . For horizontal centering, you could either add text-align: center to center the text and any other inline children elements.

How do you center an element with position fixed?

You basically need to set top and left to 50% to center the left-top corner of the div. You also need to set the margin-top and margin-left to the negative half of the div's height and width to shift the center towards the middle of the div.


1 Answers

Without using JavaScript, you can use nested divs with overflow properties:

Nest two rows of divs inside a parent div. Your horizontal scrollbar should be from your bottom nested div (your top nested div should have no horizontal scrollbar). Your vertical scrollbar will be from your parent div (your nested divs will have no vertical scrollbars).

Then, if someone scrolls vertically, both nested divs will scroll. If someone scrolls horizontally, only your bottom nested div will scroll (the top nested div will appear fixed).

like image 151
Will Peavy Avatar answered Oct 19 '22 10:10

Will Peavy