Css position fixed margin left

How to position a div left to another div and top fixed to body?

I would like to add a menu left to a div but fixed relative to the top of the body. So when I scroll the div, the left menu sticks to the screen.

.container < position: relative; width: 70%; margin-right: auto; margin-left: auto; height: 1300px; background-color: grey; >.menu_fixed_left < position: absolute; left: -50px; width: 50px; margin-top: 100px; z-index: 2; background-color: silver; >ul

-> insertusernamehere : with position:fixed, the left menu doesn’t stick to the main div left border when the width of the screen is modified.

4 Answers 4

You will have to follow some steps:

  • First of all, you will have to display your menu as fixed .
  • Second, to position it on the top of the body , you will have to use top: 0 (or you can change it to your desired top taking as reference the body tag).
  • As the content div occupy the 70% of the width of the screen with margin: auto it means that it has 15% (30% that is not occupy and the same at each side, 30%/2 = 15%) of the screen on each side so you will have to use calc to rest to the 15% of each side, the 50px that occupy your menu.
  • Remove the default margin of your body tag.

@Juanín What I can understand from the question is that he wants it on the top of the body but I will wait until he tell something. Anyway, I let him know that he can change the value for its desired top taking as reference the body tag).

@Vincent Be aware that using margin-top: 100px you are occupying a space and with top: 100px you will not.

Источник

Center aligning a fixed position div

. where the value for margin-left is half the width of the div. This doesn’t seem to work for fixed position divs, instead it just places them with their left-most corner at 50% and ignores the margin-left declaration. Any ideas of how to fix this so I can center align fixed positioned elements? And I’ll throw in a bonus M&M if you can tell me a better way to center align absolutely positioned elements than the way I’ve outlined above.

16 Answers 16

Koen’s answer doesn’t exactly center the element.

The proper way is to use CSS3 transform property, although it’s not supported in some old browsers. We don’t even need to set a fixed or relative width .

 
I'm almost centered DIV lorem ipmsum
I'm exactly centered DIV using CSS3

thats perfect. I used this for a cordova application & its expected to run in major updated browsers 🙂

Читайте также:  Kotlin data class nullable

Wow — thanks! I’ve been trying to center text between two uneven divs and this is the only one that works without destroying the markup!

@Alex left: 50% moves the div to the 50% of the page. But you have to keep in mind that it moves it starting from the left side of the div, therefore the div is not centered yet. translate(-50%, 0) which is basically translateX(-50%) considers the current width of the div and moves it by -50% of its width to the left side from the actual place.

For the ones having this same problem, but with a responsive design, you can also use:

width: 75%; position: fixed; left: 50%; margin-left: -37.5%; 

Doing this will always keep your fixed div centered on the screen, even with a responsive design.

You could use flexbox for this as well.

I’ve altered my answer by removing the mention to

which was deprecated and by using a modern technique like the display: flex and some associated properties.

From the post above, I think the best way is

  1. Have a fixed div with width: 100%
  2. Inside the div, make a new static div with margin-left: auto and margin-right: auto , or for table make it align=»center» .
  3. Tadaaaah, you have centered your fixed div now

This is also the only way I know of to allow max-width s for fixed-position elements. You want a fixed sidebar that responsively takes 30% of your max-width: 1200px web page? This will get you there.

display: fixed; top: 0; left: 0; transform: translate(calc(50vw - 50%)); 

Center it horizontally and vertically (if its height is same as width):

display: fixed; top: 0; left: 0; transform: translate(calc(50vw - 50%), calc(50vh - 50%)); 

No side effect: It will not limit element’s width when using margins in flexbox

This is better than using left: 50%; transform: translate(-50%, 0); , as it avoid showing of a horizontal scrollbar when 50% of centered widget > 50vw on Firefox.

Normal divs should use margin-left: auto and margin-right: auto , but that doesn’t work for fixed divs. The way around this is similar to Andrew’s answer, but doesn’t use the deprecated thing. Basically, just give the fixed div a wrapper.

This will center a fixed div within a div while allowing the div to react with the browser. i.e. The div will be centered if there’s enough space, but will collide with the edge of the browser if there isn’t; similar to how a regular centered div reacts.

If you want to center aligning a fixed position div both vertically and horizontally use this

position: fixed; left: 50%; top: 50%; transform: translate(-50%,-50%); 

If you know the width is 400px this would be the easiest way to do it I guess.

Читайте также:  Javascript div style scroll

The conventional approach of .center < position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); >tries to keep some empty space around the centered element which often causes the centered element’s width to not be ideal like being smaller than what it should be.

@proseosoc’s answer works well in that scenario and extends the centered element’s reach to the end of the viewport sides. The centered element, however, gets centered to the entire viewport including the scrollbar. But if your use case requires centering elements within space without the scrollbar, you can use this modified answer. This approach is also similar to the aforementioned conventional approach which centers elements in space without the scrollbar.

Center horizontally

Center vertically

Center horizontally and vertically

Источник

Как работает position: fixed;

Элемент с position: fixed; фиксируется в рамках области просмотра страницы, будь то в окне браузера или в iframe , расстояние до края которой указано в свойствах top , right , bottom , left . Передвинуть его относительно своего расположения можно с помощью margin и transform . Размещение элемента над другими элементами правится с помощью свойства z-index .

После того, как свойство position примет значение fixed , размер элемента может измениться, а соседние элементы сдвинутся на освободившееся пространство.

«Приклеить» элемент, чтобы он не менял своего положения при прокрутке страницы

Элемент с position: fixed; не влияет на размер родителя.

  
static
fixed

Элемент с position: fixed; не влияет на положение соседей: цифры 20, 21, 22, … смещаются к цифре 19.

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 static 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 fixed 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

В отличии от элемента с position: absolute; без родителя с position не static , элемент с position: fixed; не меняет своего положения при скроллинге.

  absolute fixed

При отсутствии свойств top , right , bottom , left элемент фиксируется на том месте окна браузера либо iframe , на котором находился до прокрутки. Его не увидеть, если он был ниже области, видимой без прокрутки.

  
fixed
fixed
fixed

Расположить элемент с position: fixed; относительно области просмотра окна браузера, iframe и т. п.

Свойства top , right , bottom , left могут иметь как положительные, так и отрицательные значения в любых единицах измерения, а также в процентах. По умолчанию у них установлено значение auto .

  top right bottom left auto

Значения свойств height , top и bottom в процентах рассчитываются от высоты области просмотра. Свойство height в процентах не заменяется на height: auto; , даже когда ближайший родитель имеет height: auto; . Значения свойств width , margin , padding , left и right в процентах рассчитываются от ширины области просмотра.

  

Ширина и высота элемента с position: fixed; относительно области просмотра

Ширина элемента с position: fixed; без явно заданного значения устанавливается по содержимому. Элементы с display не block и position: fixed; ведут себя как элементы с display: block; и position: fixed; .

  
Блочный
Строчный

Без явно заданной ширины и/или высоты размер элемента определяется расстоянием от left не auto до right не auto и/или от top не auto до bottom не auto (для IE8+).

  
Элемент

Стили, чтобы растянуть блок на всю ширину и высоту области просмотра окна браузера, iframe и т. п.:

left: 0; right: 0; top: 0; bottom: 0; /* или */ left: 0; right: 0; width: 100%; height: 100%; box-sizing: border-box;

С ограниченной шириной и/или высотой расстояние от left не auto до right не auto и/или от top не auto до bottom не auto определяет область, в рамках которой может перемещаться элемент с margin: auto; (для того, чтобы передвинуть элемент в центр верхней правой 1/4 части родителя см., left: 50%; right: 0; top: 0; bottom: 50%; ). Если расстояние от left не auto до right не auto меньше width , то свойство right игнорируется (см., left: 50%; right: 50%; ).

  
Элемент

position: fixed; и overflow не visible

Выходящая за границы родителя с overflow отличным от visible часть элемента с position: fixed; не будет скрыта. Даже если она выйдет за рамки области просмотра, горизонтальная или вертикальная полоса прокрутки не появится.

  
Элемент

position: fixed; и clip-path или clip

Свойство clip не рекомендуется использовать, так как оно устарело. Ему на смену пришло clip-path . Элемент с position: fixed; не выходит за рамки родителя с одним из них.

 /* серым выделено то, что нужно только для clip, так как он работает лишь совместно с position: absolute; */ body < height: 500vh; >.parent .absolute < position: absolute; width: 100%; box-sizing: border-box; height: 5em; border: 1px solid red; clip: rect(0, auto, auto, 0); /* весь периметр родителя */ clip-path: polygon(0 0, 0 100%, 100% 100%, 100% 0); /* весь периметр родителя */ > .fixed < /* одинаковое положение для обоих элементов */ position: fixed; top: 1em; left: 5%; > .fixed.red < background: red; >.fixed.lightpink 
Зафиксированный
Зафиксированный

position: fixed; не работает, когда у родителя свойства transform , perspective , filter или will-change имеют значение не none

Элемент с position: fixed; ведёт себя как элемент с position: absolute; относительно ближайшего родителя с transform , perspective , filter или will-change не none . Они создают новый контекст наложения. В браузерах разночтение.

нет нижеприведённых transform: translateX(0); filter: blur(0); perspective: 0; will-change: transform;

 body < height: 500vh; >div > span < position: fixed; right: 0; background: lightpink; > 
Элемент

div по центру экрана

Вариант, который работает почти во всех версиях браузеров.

 #fixed < position: fixed; top: 0; left: 0; height: 100%; width: 100%; z-index: 2; text-align: center; background: rgba(0,0,0,.7); /* IE+9 */ > #fixed:before < /* IE+8 */ content: ""; display: inline-block; height: 100%; vertical-align: middle; > .fixed 
содержание

illyuziya Классно! А я всё думала, как «прилепляют» кнопочки и т.п. к краям экрана. Спасибо за «Шпаргалку. » — работа проделана колоссальная, а главное нужная. Анонимный Как сделать липкий слой чтобы находился рядом с основным блоком? NMitra Посмотрите, пожалуйста, возможные образцы.

Источник

Оцените статью