Home >Web Front-end >CSS Tutorial >How Do `position: absolute` and `position: fixed` Differ in HTML/CSS Positioning?

How Do `position: absolute` and `position: fixed` Differ in HTML/CSS Positioning?

Susan Sarandon
Susan SarandonOriginal
2024-11-29 05:30:09207browse

How Do `position: absolute` and `position: fixed` Differ in HTML/CSS Positioning?

Positioning Elements Fixed Relative to Parent or Window

In HTML and CSS, there are two main ways to position elements: relative to the parent or relative to the window.

Positioning Element Fixed Relative to Parent

To position an element fixed relative to the parent element, use the following CSS property:

position: absolute;

When an element is positioned absolute, its position is determined relative to the immediately containing parent element. For example:

#parent {
  position: relative;
}
#child {
  position: absolute;
  left: 50px;
  top: 20px;
}

In this example, the child element will be positioned 50 pixels from the left and 20 pixels from the top of the parent element.

Positioning Element Fixed Relative to Window

To position an element fixed relative to the window, use the following CSS property:

position: fixed;

When an element is positioned fixed, its position is determined relative to the viewport. For example:

#my-element {
  position: fixed;
  right: 0;
  top: 120px;
}

In this example, the my-element will be positioned 120 pixels from the top and 0 pixels from the right of the viewport.

The above is the detailed content of How Do `position: absolute` and `position: fixed` Differ in HTML/CSS Positioning?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn