What's the point of specifying position relative if it's not even needed?

Why do I see many sites setting the position: relative; in block elements when they do not use position in the inner elements? Is there any other reason to set the position relative?

For example:

<div class="parent">
  <div class="parent__container">
    other elements here.
  </div>
</div>

.parent {
  background-color: blue;
}

.parent__container {
  position: relative;
  // etc
}

Even when the inner elements are not using position, sometimes I see the .parent with position: relative; set.

This seems to be a very common practice, but is it really necessary? I can provide examples of sites that apply this without explanation.

Thank you.

Answer №1

There are three main reasons why an element is styled with position: relative:

  1. To adjust the position of the element itself, such as top: 20px

  2. To utilize z-index for stacking elements. Without a specified z-index, the element will automatically be placed on top of statically positioned elements.

  3. To constrain the positioning of absolutely positioned child elements within the relatively positioned element.


For more information on the differences between commonly used position values, check out this informative article:

Answer №2

Nowadays, the majority of websites utilize "relative" positioning to ensure flexibility and compatibility with various screen sizes, including small-screen devices like smartphones and non-16x9-conforming devices. The initial reason for choosing relative positioning over absolute positioning was to give the programmer the ability to let the web page handle positioning based on hierarchical order unless specified otherwise.

Update: It's important to note that defining "relative" assigns a certain hierarchical order to an element and its children in the DOM model. It doesn't determine the specific positioning of an element (such as aligning left or right), but rather establishes a "box" or "container" where the element and its children are structured hierarchically based on their nesting within the HTML, which the entire HTML document must adhere to. Essentially, "relative" sets the priority/hierarchy of an element in relation to its parents.

On the other hand, if a programmer wants certain elements to be statically positioned, they would use "position: absolute;" to make that element static in relation to its parent. For example:

    <div class="parentA">ParentA Text
      <div class="childA">
          All elements are placed absolutely, requiring specific positions using margins, alignment, etc. This behavior may or may not be inherited depending on the browser and code structure.
      </div>
    </div>
    <div class="parentB">ParentB Text
      <div class="childB">
          All elements are placed relatively, not needing specific positions using margins, alignment, etc., unless desired. This enhances the webpage's flexibility in element positioning.
      </div>
    </div>
    <div class="parentC">ParentC Text
      <div class="childC">
          All elements within and under childC are positioned absolutely in relation to parentC, necessitating defined positions using margins, alignment, etc.
          <div class="grandChildC">
          Grandchild
          </div>
      </div>
    </div>
    <style>
    .parentA {
        position: absolute;
    }
    
    .parentB {
        position: relative;
    }
    
    
    .parentC {
        margin: 60px;
    }
    .childC {
        position: absolute;
    }
    </style>

As illustrated above, because parentB is relative, it picks up where parentA left off. As parent A has no size and is defined as an absolute/static object, the two divs overlap. Conversely, since parentC is relative and childC is absolute, childC will align with parentC's position, but its layout will remain static and on top of other elements, maintaining a fixed position relative to parentC.

I trust that this explanation addresses your inquiry. If not, please clarify your question further.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing CSS image properties: A step-by-step guide

I've come across a strange conflict between Twitter Bootstrap (2.2.1) and Ad-Gallery in Internet Explorer. It seems that certain lines in bootstrap.min.css are causing issues, preventing images from displaying: img{max-width:100%;width:auto\9;h ...

expanding menu options in a dynamic design

My webpage features a logo alongside a menu: Here's the HTML code: <div id="logomenuwrapper"> <div id="logo"><img src="img/logo_light.jpg"/></div> <div id="menu"> <ul> <li><a href="#">About ...

The jquery script for the dynamic remove button is malfunctioning

I have successfully implemented code to display dynamic controls using jQuery. Below is the working code: <script type="text/javascript"> $(document).ready(function() { $("input[value='Add']").click(function(e){ e. ...

Organize text documents for website display

Is there a way to code a website that will showcase the 20 most recent text files from a directory, in descending order of newest to oldest, and provide links for viewers to access them on the web? ...

Choose the element before and add a style effect with CSS

I'm trying to create a layout with 3 <div> elements in one horizontal line, each with a width of 33.33%. When hovering over one div, I want its width to expand to 50% while the other two shrink to 25%. <div id="A"></div> <div id= ...

Ways to prevent the :link style being applied to every link

Is there a way to apply this CSS styling to only one specific link and not all the links on my page? Here is the CSS code that is currently being applied to all links: a:visited { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; font-size: 14px ...

Adding a semi-transparent layer to cover half of the canvas while still allowing the canvas to be visible

I'm struggling with overlaying a div on top of a canvas while keeping the canvas visible. Currently, I can only get the div to cover the canvas and hide it. If anyone has an example to share, that would be greatly appreciated. var canvas = document ...

The functionality ceases to operate properly once a new element has been added

I am encountering an issue with the "click" action on a newly created element through a jQuery function, as it is not functioning properly. To demonstrate this problem, I have set up a JSFiddle at the following link (JSFiddle), however, please note that t ...

What is the process for implementing hover transitions on link elements?

I am trying to incorporate a transition effect for my links. Essentially, I want the text-decoration (which is currently set to underlink) to gradually appear. Unfortunately, my previous attempt at achieving this has been unsuccessful: #slink{ transit ...

Ways to quickly change a class when clicking (without waiting for mouse button release)

Is there a way to instantly change the color of my span element when it's clicked by the user, rather than waiting for the mouse button to be released? This is the CSS code I'm using for the class: span.active{ color:#bdbcae; } I've tri ...

Troubleshooting issue with alignment in Material UI using Typescript

<Grid item xs={12} align="center"> is causing an issue for me No overload matches this call. Overload 1 of 2, '(props: { component: ElementType<any>; } & Partial<Record<Breakpoint, boolean | GridSize>> & { ...

Internet Explorer having trouble with onload function

Here is a snippet of code that I am working with: <html> <head> <style> #visibilitycontent{ visibility:hidden; } </style> </head> <body onload="visibilitychange()"> <div id="header"> This is the h ...

Creating a responsive image using Bootstrap with an SVG filter applied

I've been working on applying an SVG filter to responsive images in Bootstrap 4 by using the class "img-fluid" However, I'm facing an issue where the separation between images varies across different resolutions. It's fine on desktop, but o ...

What is the reason behind lightbox not disabling scrolling?

While using the default lightbox2 CSS and JavaScript, everything is functioning correctly except for an issue on Safari mobile. When I click an image and the lightbox opens, swiping to the left reveals blank white space despite having overflow-x set to hid ...

An issue arises in CSS when the styling is not correctly implemented on the HTML elements

I am currently trying to recreate this code on my own page: https://codepen.io/Vlad3356/pen/PoReJVg Here is the code I have written so far: https://codepen.io/Vlad3356/pen/GRxdMPz I'm puzzled as to why, when I click on a star in my version of the co ...

Attempting to grasp the fundamentals of angular Routing, however, upon attempting to reload the page, nothing appears to be displayed

While working in the Bracket editor, I created a file structure with various files located under the 'scripts' tags within the Index.html file. The root folder is named 'projectAngular', inside which there are subfolders like 'appC ...

Customize default zoom settings with Cascading Style Sheets (CSS)

body{ margin-bottom: 10%; margin-left: 10%; width:80%; color: #264653; position: relative; } #photo{ border-radius: 70%; position: absolute; left: 25%; top: 50px; } .left1{ margin-top: 10%; background-color: #264653; width : 30%; ...

Enhancing the appearance of a checkbox within a ReactJS setting

I'm having trouble customizing a checkbox in a ReactJS environment for IE11. I've tried various approaches, but nothing seems to work. Can anyone offer any advice? Here is the code snippet: CSS: .squared { input[type=checkbox] { bo ...

How can I incorporate dynamic moving lines into my website's loading sequence?

Link to Gyazo image 1: https://gyazo.com/015425f0decb187e28b620c1e3206391 Issue with first image: https://gyazo.com/dfcd33e8a4fd5bea64e51fe40556f0bf I'm currently working on a website and came up with a cool concept of having two lines crossing the s ...

Steps to create full screen jQuery tabs with overflow scroll feature in the content

I am in the process of creating a responsive web design using jQuery tabs. My goal is to make one page of the website occupy the entire screen (100% height and width), have a fixed height for the div.ui-tabs-nav, and enable scrolling for the content of div ...