Positioning Elements with CSS Relative and Absolute Placement

I am relatively new to the world of web design and currently grappling with the concept of positioning in CSS. I have a basic understanding of relative and absolute positioning for elements. In the code snippet below, there is a <div> that acts as the parent to both a <p> and a <span>. Interestingly, when I set the p element to position:absolute, the border seems to overlap, whereas when I apply the same style to the <span>, everything falls into place quite nicely (allowing me to move the text within the border). Can someone please explain why this discrepancy is happening and what I might be missing here?

div {
  position: relative;
  border: 2px solid black;
  padding: 10px;
}

p {
  position: absolute;
  top: 10px;
}

span {
  top: 10px;
}
<div>
  <span>possessions</span>
  <p>
    Five suspected gang members attacked two agents who were escorting them in a lift, the Investigative Committee said. The group was handcuffed and it wasn't immediately clear how they managed to free themselves to attack the guards. The two other suspects
    and three security officers were wounded. The suspects were accused of being part of a group known as GTA Gang, named after the violent game series Grand Theft Auto. The group of Central Asian nationals was suspected of killing 17 motorists in the
    Moscow area between 2012 and 2014. Cars were forced to stop on a main road and their drivers were killed for reasons as yet unknown; none of their belongings were stolen.
  </p>
</div>

Answer №1

When the position of an element is set to absolute or fixed, it is completely removed from the normal flow of the document.

For example, setting the position:absolute for a p element removes it from the normal flow causing the border to crash. However, if you don't define a position for the p, it will have the default static position and remain in the flow without causing any issues with the border.

To avoid this issue, consider using position:relative instead of position:absolute for the p element.

div{
  position:relative;
  border:2px solid black;
  padding:10px;
  
  }
  
  p {
   position:relative;
   top:10px;
  }
  
  span{
   position:absolute;
   top:10px;
  }
<div >
<span>possessions</span>
<p>
Five suspected gang members attacked two agents who were escorting them in a lift, the Investigative Committee said.
The group was handcuffed and it was not immediately clear how they managed to free themselves to attack the guards.
The two other suspects and three security officers were wounded.
The suspects were accused of being part of a group known as GTA Gang, named after the violent game series Grand Theft Auto.
The group of Central Asian nationals was suspected of killing 17 motorists in the Moscow area between 2012 and 2014. Cars were forced to stop on a main road and their drivers were killed for reasons as yet unknown; none of their belongings were stolen.
</p>
</div>

Answer №2

I suggest avoiding the use of position: absolute unless specifically necessary.

  • element overlapping other elements or overlapped by other elements
  • element removed from normal flow of document

I would advise against using position: relative unless you have a specific need for it.

  • If you want an element to act as the coordinate system for absolutely positioned descendant elements with a demo code example.

  • Ensuring that an element maintains its original space before applying positional properties with another demo code example.


If all you need is to move elements slightly, consider using margin-top in your CSS instead of positional properties. A demo showcases this approach.

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

The collapsible list feature that includes the use of plus and minus signs is malfunctioning

Below is the script that I wrote to address this issue, but for some reason the + and - swapping is not functioning correctly. $('.showCheckbox').click(function(e) { var dynamicBox = $(this).attr('val'); var collapseSign = $(th ...

What is the best way to create an HTML5 Range that gracefully degrades?

I want to incorporate the <input type='range' /> element from HTML5 for modern browsers and fallback to a <select /> if needed. Since I am working with Ruby-on-Rails, as a last resort, I could implement something similar to this on th ...

Tips for choosing a table row that is not the first or last cell

#MyTable tr+tr:hover { background: #dfdfdf; } <table id="myTable"> <tr> <td>A</td> <td>B</td> <td>C</td> </tr> <tr> <td>1</td> <td>2</td> &l ...

Reduce the height of the navigation bar

I used the header example from Bootstrap's documents here: https://getbootstrap.com/docs/5.3/examples/headers/# The code I have is: <div class="container fixed-top bg-white"> <header class="d-flex flex-wrap justify-conte ...

The runtime is experiencing difficulty in loading the Bootstrap files

File Structure in eclipse The issue is that the CSS files are not loading at runtime, causing me to lose the design I created. Below is my code for the login page. When clicking on the links for the CSS files, they open in the Eclipse IDE instead of load ...

Can you please tell me the font size specified as 20px/26px?

Recently stumbled upon the 20px/26px value in a codebase I'm currently working on. Wondering if anyone has encountered this before and knows what its purpose is. Interestingly, it renders with the latter pixel value (26px) in Chrome. #action { font: ...

Progress Indicator on my online platform

I've been attempting to remove a loading bar from my website, but I can't seem to locate it in the site files. I even tried using Google Chrome's inspection tool, but I couldn't pinpoint the loader. Can someone please assist me? Visit ...

Ways to initiate a CSS transition without hovering over it

Currently, I have a sidebar that is hidden and only shows up when the mouse hovers over it. I'm wondering how I can make the CSS transition trigger before the mouse hover, similar to what happens in this sidebar link: . Any advice on how to achieve th ...

Contrasting flexbox overflow handling in React versus React Native

As a beginner in React Native, I have a query about achieving a flex layout with two child containers. The goal is to ensure that if one child's content overflows, the other child shrinks accordingly. In standard HTML/CSS, I was able to achieve this: ...

"Step-by-step guide for incorporating a right-to-left (RTL) Bootstrap

Is there a way to make my bootstrap navbar right-to-left (RTL)? I want the logo to be on the right and the links to flow from right to left. I've tried various tricks but none of them seem to work. Here's the code I currently have: <nav class ...

As the number of lines increases by x%, CSS gradients gradually fade away during the generation process

Is there a way to create a gradient that displays a red line every x% without the colors fading into white? As I add more lines, the red stripes seem to lose their intensity and blend into a white background. The .four-stripes selector creates a good resu ...

Generate text in reStructuredText with columns

I'm attempting to style a reStructuredText segment in the following layout: type1 : this type4 : this type7 : this type2 : this type5 : this type8 : this type3 : this type6 : this type9 : this I want to fill the page with tex ...

Is there a way to locate and delete an image element with a broken hyperlink?

My website is currently hosted on Wordpress, and I've noticed that there is an issue with a broken image link on my site. I'm not sure when this occurred, but it seems to only be affecting the post section of my site. https://i.sstatic.net/iarDU ...

Position navbar contents at the top of the screen

As I delve into learning Bootstrap4, I have come across the following snippet of HTML code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

After the rendering of the HTML, the value of the jQuery input does not change

Here we have a function that loads HTML onto the form class in a file. The quest[q] locates the appropriate HTML template to load from an array of templates. The HTML being loaded contains an input with an id of "p". I am attempting to set the value of th ...

display the table without providing a preview

Hey everyone, I am currently utilizing vue.js to develop a table and I am looking for a way to add a button that can print the data in the table without displaying a preview dialog. What modifications should I make to my javascript code in vue? Here is an ...

Establishing a primary color for all text in Vuetify

How can I set a base color for all text in a Vue + Vuetify project? I attempted to change the theme's primary color in vuetify.ts: export default new Vuetify({ theme: { themes: { light: { primary: "#E53935", }, }, }, } ...

Add some text onto the Box Component in Material UI

I am looking to replicate the hover functionality (UI) seen in this example: Desired UI Source: Since adjusting background image styles can be complex, I have opted to use the Box Component from Material UI. Within the Box Component, I have implemented th ...

Having trouble getting Bootstrap 4 SCSS overrides to take effect?

Let's dive into a quote from the Bootstrap documentation: Each Sass variable in Bootstrap 4 comes with the !default flag, allowing you to modify the default value in your own Sass even after that original variable has been set. Here is the content ...

Troubleshooting Issues with Implementing JavaScript for HTML5 Canvas

I've encountered an issue with my code. After fixing a previous bug, I now have a new one where the rectangle is not being drawn on the canvas. Surprisingly, the console isn't showing any errors. Here's the snippet of code: 13. var can ...