search

Home  >  Q&A  >  body text

The difference between static positioning and relative positioning

<p>In CSS, what is the difference between static (default) positioning and relative positioning? </p>
P粉316423089P粉316423089460 days ago633

reply all(2)I'll reply

  • P粉649990273

    P粉6499902732023-08-23 14:56:53

    For the answer to "Why does CSS still implement position:static;", in some cases, using position:relative for the parent element and position:absolute for the child element will limit the scaling width of the child element. In a horizontal menu system you may have linked 'columns', which using width:auto won't work with relative parent elements. In this case, changing it to 'static' will allow the width to change based on the content within it.

    I spent hours struggling with why the container couldn't be resized based on its contents. Hope this helps!

    reply
    0
  • P粉122932466

    P粉1229324662023-08-23 13:24:51

    Static positioning is the default positioning model for elements. They are rendered on the page as part of the normal HTML flow. Static positioned elements do not obey the left, top, right, and bottom rules:

    Relative positioning allows you to specify a specific offset relative to an element's normal position in the HTML flow (such as left, top, etc.). So if I have a textbox within a div, I can apply relative positioning to the textbox so that it appears relative to where it would normally be placed within the div Specific location:

    There is also absolute positioning - you can specify the exact position of the element relative to the entire document, or relative to the next relatively positioned element higher level in the element tree:

    When position: relative is applied to the parent element in the hierarchy:

    Please note that our absolutely positioned elements are limited by relatively positioned elements.

    Finally there is fixed positioning. Fixed positioning constrains an element to a specific location in the viewport that remains unchanged during scrolling:

    You can also observe that fixed positioned elements do not cause scrolling because they are not considered viewport constrained elements:

    Absolutely positioned elements are still limited by the viewport and will cause scrolling:

    Unless of course your parent element uses overflow: ? to determine the behavior of scrolling (if any).

    Using absolute positioning and fixed positioning, the element will break out of the HTML flow.

    reply
    0
  • Cancelreply