Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS display:block and position:fixed

Tags:

html

css

Why will this code:

div {
    background-color: yellow;
    display:block;
    position:fixed;
}

not display the div as display:block (i.e. flow across the page) when I add position:fixed? It seems to work otherwise?

N.B. I am very new to CSS so I appologise if it is just a silly error

like image 236
Sebiddychef Avatar asked May 19 '13 20:05

Sebiddychef


People also ask

How do you keep position fixed in CSS?

The interesting rule here is the ' position: fixed ', that makes the DIV stay fixed on the screen. The ' top: 50% ' and ' right: 0 ' determine where the DIV is displayed, in this case: 50% down from the top of the window, and a constant 0px from the right.

How do you keep a position fixed in a div?

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.

What is the difference between display and position in CSS?

Position property determines in what manner an item is positioned on the page or relative to one another. CSS's Display property specifies the type of rendering box that is created from our HTML you can say it like block, inline, inline block, flex.

What can I use instead of fixed position?

An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.


2 Answers

When you use position: fixed; or position: absolute;, the element is taken out of the regular flow of the document.

The default setting for width for a div element is auto, which means that it will use the full available width where it is. When you take it out of the flow, there is no longer any usable measure for available width (because that would be infinite), so instead the element will get its width from its content.

like image 168
Guffa Avatar answered Sep 18 '22 22:09

Guffa


You need to add width and height to any [empty] elements with position either fixed or absolute, otherwise they won't have any size.

html, body {
  height: 1000px;
}

div {
    background-color: yellow;
    display:block;
    position:fixed;
    width:100px;
    height:100px;
}
<div></div>

Finally u need something like this

like image 21
underscore Avatar answered Sep 17 '22 22:09

underscore