Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Fixed position with Auto Margin

Tags:

I want a component that keeps horizontal center of the page (two-columns), and I have a sub-component (right column) that I want its position to be fixed, so the sub-component's position to be fixed, but the whole two columns to be centered.

#content {     width: 1200px;     height:auto !important;     height:100%;     min-height:100%;     padding-top: 42px;     padding-bottom: 100px;     margin-auto: 0 auto;     position: relative; }  #left {     width: 700px;     float: left; }  #right {         width: 500px;         position: fixed;         top: 0px; } 
like image 551
bernardw Avatar asked Jul 12 '10 21:07

bernardw


People also ask

Does margin work with position fixed?

Margin does not work because position of the header is fixed.

How do you give a position to margin fixed?

You can use margin: 0 auto with position: fixed if you set left and right . This also works with position: absolute; and vertically.

How do you set a fixed margin in CSS?

Values. The size of the margin as a fixed value. The size of the margin as a percentage, relative to the inline size (width in a horizontal language, defined by writing-mode ) of the containing block. 0 , except if both margin-left and margin-right are set to auto .

How do I fix fixed position in CSS?

Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute , but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.


2 Answers

You can use margin: 0 auto with position: fixed if you set left and right.

.wrapper {     position:fixed;     top: 0;     left: 0;     right: 0;     width: 500px;     margin: 0 auto; } 

This also works with position: absolute; and vertically.

Demo: http://codepen.io/pstenstrm/pen/myaWVJ

like image 150
pstenstrm Avatar answered Sep 21 '22 10:09

pstenstrm


You cant do that with margin:auto, but you can do something like this:

#CSS-SELECTOR-YOU-ARE-USING{     background:#FF0000; // Just so you can see whats going on     position:fixed; // Position the element     right:50%; // Move it to the right for 50% of parent element     margin-right:-250px; // You need here to put 1/2 of what you have below in width     width:500px; } 

This way you move element to the right for 50%, and then move it back for half of its width. That way you get centered element with position:fixed.

like image 33
Gavrisimo Avatar answered Sep 22 '22 10:09

Gavrisimo