CSS and the art of absolute positioning

My grasp of CSS positioning was solid until I stumbled upon this straightforward code snippet (also available in JSFiddle).

#outer {
  /*position: absolute;*/
  box-shadow: inset 0 0 3px red;
}
#inner {
  box-shadow: inset 0 0 3px blue;
  /*position: absolute;
    left: 15px;*/
}
<p id="outer">outer
  <p id="inner">inner</p>
</p>

What bewilders me are the following:

  1. If you remove the comment from the first position: absolute; rule, why does the outer paragraph not overlay the inner one? Since the outer paragraph lacks any non-static parent, it should be positioned with respect to the browser window, shouldn't it?
  2. Uncommenting the first rule and then setting position: absolute; left: 15px; for the inner paragraph causes the element to shift downwards. Why does this happen?

Answer №1

The positioning of outer remains unchanged because the default margin of both inner and outer prevents it from moving upwards, which may not be what you were anticipating.

Similarly, in your second inquiry, the presence of margins and line-height in inner impacts its display. Experiment with adjusting these attributes to zero or different values to observe the outcome.

Additionally, I noticed a flaw in your HTML code. A <p> element should not enclose another <p> element.

Answer №2

Disclaimer: The markup used in this code snippet may not comply with W3C HTML Validator standards, which could lead to inconsistent results. A recommended refactor would involve wrapping the #inner tag in a <span></span> element and applying appropriate styling.

In response to Question 1: This behavior occurs because an element given a position: absolute: rule without a parent element containing a position: relative; rule will be positioned relative to the browser window and excluded from the document flow. Consequently, the #inner element will disregard the #outer element and assume its place in the document flow.

Regarding Question 2: The spacing issue is due to default margins applied to the <p></p> tag. Refer to the linked screenshot for visual contexthttps://i.sstatic.net/uRM51.png

Answer №3

It is important to note that block level elements are not allowed inside the p tag. http://www.w3.org/TR/html401/struct/text.html#h-9.3.1

When the browser receives your original HTML, it detects the invalid structure and attempts to correct it.

The browser identifies the issue with nested p tags and automatically adds a closing p tag after the text "outer". This then necessitates the addition of an opening p tag for correctness.

The resulting HTML generated by the browser includes these corrections, which may differ from what you intended:

<p id="outer"> outer</p>

<p id="inner"> inner </p>

<p></p>

This discrepancy in the code structure can lead to unexpected results when rendered on the web page.

Answer №4

Initially, it is important to note that a <p> element should not enclose another <p> element. Both #inner and #outer are considered as <p> elements, which inherently have a default display of block along with top and bottom margins.

  1. Upon setting #outer to position: absolute, inspection will reveal that #outer is positioned relative to its initial ancestor element - the <body>.

  2. In order to demonstrate this effect, consider altering your code as follows:

    <div id="outer">outer 
        <p id="inner">inner</p>
    </div>
    

    Now, upon applying position: absolute and left: 15px to #inner, it becomes relative to its ancestor element - #outer.

If the intention is for #inner to overlap #outer, modify the display property of both elements to display: inline;, apply position: absolute solely on #inner, and eliminate the position value from #outer.

Keep in mind: position: absolute signifies that the element is positioned relative to its first positioned (non-static) ancestor element.

Refer to this demo for further clarity.

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

Conceal Outcomes, W3Schools PHP Example AJAX Interactive Search

Currently, I am experimenting with the Ajax Live Search feature on the W3Schools website. It's functioning well, but I would like the results to hide when the user clicks away from them. I discovered a code snippet that achieves this, but I'm str ...

VueJS can manipulate an inline template by dynamically changing its content and reinitializing

this particular query shares similarities with the discussions on VueJS re-compiling HTML in an inline-template component as well as How to implement Vue js directive in an appended html element Regrettably, the approach suggested in those threads is no l ...

The height of the li element is not properly aligning with the height of

I am having some trouble with creating a menu panel. I have set the height for both the li and menu div to be the same, but there appears to be a margin at the bottom of the li. I would like the li to completely fill the menu height. Any help is greatly a ...

Merging a generator of unpredictable quotes with a simulated typewriter effect

Recently, I've been experimenting with a project involving a random quote generator and wanted to add a typewriter-style animation when the generator displays a new quote. The challenge is that my knowledge of JavaScript is quite limited, making it di ...

What is the best way to apply transparency to a color using its hex value in CSS?

Opacity can be added to hsl values using the following syntax: background: hsla(213, 34%, 12%, .5); Similarly, opacity can also be applied to rgb values like this: background: rgba(134, 231, 54, .5); But have you ever wondered how we can add opacity to h ...

Exploring the analysis of JavaScript and CSS coverage throughout various pages or websites

The Chrome Dev Tools JavaScript and CSS Coverage Drawer is quite impressive, but there is one thing that could make it even better. It would be great if it could remain active without restarting its analysis every time you visit a new page. I wish I could ...

What is the process for implementing the sticky table header jQuery plugin?

I am looking to implement a sticky header on all tables in my web application, which is built on PHP. As the amount of data continues to grow, search results are fetching more records that may not be visible. I am primarily a PHP programmer and do not have ...

Issues with organizing a Portfolio Gallery

Currently, I am in the process of creating a portfolio page and I am utilizing placeholder images until I have actual projects to showcase. I am encountering difficulties trying to structure one large image with two to four smaller images underneath it, al ...

problem with hiding bootstrap dropdown

Having trouble with Bootstrap, the dropdown menu is not hiding when I hover over the link. I want the dropdown to only show when I hover over it. Any help would be appreciated. Here is the code snippet: <nav> ...

How can I make either the left or right section remain sticky for a certain period of time?

Can someone help me figure out how to fix a specific section in place temporarily, similar to the example provided below? In the link above, the Apple Watch product stays fixed while the content on the right moves partially, eventually causing the entire ...

Tips for showcasing information beneath a title on a webpage in Yii2 without duplicating the header

Looking to pass an array to my view that includes headings and corresponding content lists. The structure of my array is as follows: Array ( [0] => Array ( [trimester] => Trimester1 [subject] => ABC ) ...

Struggling to implement a click event followed by DOM manipulation

Every time I start the game, 4 characters are randomly generated in my starting function, and then they are displayed in the Character Div. The next step is to click on one of the four characters (vader, stormtrooper, luke, or yoda). Once a character is cl ...

Changing the color of asterisks for required fields in WooCommerceWould you like to modify

Looking for a solution to change the color of the asterisk (*) in required fields on WooCommerce forms due to accessibility issues flagged by WAVE scan. Does anyone know of a CSS code that can help with this? ...

What is the best way to show a timestamp on a website and automatically end a session after a set period of time

Is there a way to condense this code that displays the current timestamp (IST)? <?php echo date("D M d, Y "); ?> </b> <body onload="digiclock()"> <div id="txt"></div> <script> function digiclock() { ...

Page rotates on hover effect with RotateY

How can I get an image to rotate on the Y axis when hovered over? My code works in -moz- but not in -webkit- or -o-. What am I missing? .spin-logo { height: 450px; margin: 0 auto; -moz-transition: transform 2000ms ease 0s; -o-animation: transfor ...

Slider displays images generated by PHP in a horizontal motion

Currently, I am in the process of creating a custom horizontal slider for my client's personalized gallery. The gallery comprises elements displayed as a no-wrap, multi-window-width block, designed to change its margin-left when the slider arrows are ...

Is the radio functionality and dropdown menu experiencing technical difficulties?

I'm having issues with my code, specifically in the JS function when I try to retrieve values from radio buttons and dropdown menus. Can someone help me figure out what's going wrong? CSS: #mytable { width:400px; border: 1pt solid blac ...

How can I clear the value of "token-field" data in jQuery after successfully submitting a form?

I've attempted to reset the value: <input type="text" class="token-field" name="meta_keyword" id="meta_keyword" value=""> $('#meta_keyword').val(); However, it doesn't seem to be functioning as expected. ...

Aligning the Twitter and Facebook buttons

Issue with Social Media Button Alignment I'm encountering a problem with aligning Twitter and Facebook buttons on my website. The alignment seems to be off and I need some help fixing it. Code Snippet html: <span id="social"> ...

How can I prevent users from clicking the same link multiple times in HTML?

Is it possible to disable the href after one click using javascript or jquery? I need some assistance with this. Please help. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xml ...