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
Release: 2024-11-29 05:30:09
Original
156 people have browsed it

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;
Copy after login

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;
}
Copy after login

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;
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template