Inherit margins from child elements with fixed positions

Below is a very basic code example to consider:

<div id="parent">
 <div id="child">
    Test it
 </div>
</div>

This code snippet includes the following CSS styles:

#parent{
position:relative;
margin-left:200px;
color:#FFF;
}
#child{
position:fixed;
top:30px;  
background-color:red;
}

I assumed that the child div wouldn't inherit the margin-left property from its parent div due to breaking the normal flow. Surprisingly, not only does it inherit the 200px margin, but when attempting to assign a left margin of 50px to the child div, the result shows a total left margin of 250px! Why does this happen and how can I change it?

Thank you

Find the Jsfiddle link here: http://jsfiddle.net/rCMx2/

Answer №1

If you don't specify horizontal positioning axes (left: ... or right: ...), a child element will still be positioned horizontally as if it weren't fixed. The same goes for vertical axes (top: ... or bottom: ...) and its vertical position.

Even though the element is fixed, it will stay in its original position without moving when these properties are not defined.

In essence, using position: fixed and top: ... won't change the horizontal position of the element, only its vertical position. The horizontal position remains unchanged.

To solve this issue, add left: ... or right: ... to the fixed element to detach it from its initial horizontal position.

Answer №2

By adding a margin of 50px on top of the margin for your parent element, you can visually see how it affects the layout:

#parent{
  margin-left:200px;
  color:#FFF;
  border:2px solid #f0f;
  overflow:visible;
}

#child{
  top:30px;  
  background-color:red;
  margin:20px;
  border:2px solid #0f0;
}

Give it a try and see if you can better understand how the margins work without the "position" attributes included.

To create a more specific layout, it's important to clarify what you envision for the final result.

Answer №3

She takes over the position of a 200px parent div that is currently on. Since the child div is fixed, it references the parent to continue flowing independently.

You have the option to detach the child div from its parent, separating them completely.

Also, align the fixed div to be 50px from the left instead of using margin-left: 50px.

I hope this explanation clarifies things for you.

For more information, please check out this example:

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

Utilizing Ajax Blob URL for Audio Streaming

My goal is to retrieve audio data using an Ajax request and load it into an audio element. However, I'm running into an issue where the player does not seem to work properly. The play button remains disabled as if nothing has been loaded. Below is a s ...

Why can't we use percentages to change the max-height property in JavaScript?

I am currently working on creating a responsive menu featuring a hamburger icon. My goal is to have the menu list slide in and out without using jQuery, but instead relying purely on JavaScript. HTML : <div id="animation"> </div> <button ...

Develop an onclick function with an href attribute

I am interested in transforming links into AJAX versions whenever possible. To achieve this, I plan to implement a function called replaceLinks that will add an onClick handler to each link on the page and trigger ajaxPageWSM(href). This is what I currentl ...

Button Hover Effect: Transition with Style

I am trying to implement a one-second transition from the default color scheme to the hover color for a Button element in Material UI. I am using the transitions.create(props, options) method as described in this article: https://medium.com/@octaviocoria/c ...

Does the frame take precedence over the button?

const div = document.createElement('div'); // creating a dynamic div element div.setAttribute('id', "layer1"); // setting an id for the div div.className = "top"; // applying a customized CSS class div.style.position = "absolute"; // sp ...

Adjust background image size to fit the screen, not just the content

Whenever I set the background image for each page using the following JavaScript code, var imageUrl = 'url(' + imageUrl + ') top left no-repeat fixed'; $('body').css({ 'background': imageUrl }); I also add ...

Is there a way to assign a specific color to individual users in a chat?

I have successfully implemented a chat feature using Pusher, but now I want to customize the appearance by changing the color of the username for the logged-in user when they are active in the conversation. Currently, both my username and another user&apos ...

Retrieve only the initial tag content using jquery

My goal is to extract the "22" from the following code... <div class="left"> <a class="count-link" href="http://url1.com"> <span>22</span> users </a> <a class="count-link" href="http://url2.com"> <span>10</span ...

Unable to access localStorage

I created a Plunker to store a value in localStorage: <!DOCTYPE html> <html> <script> localStorage.setItem('test', "hadddddha"); </script> </html> Then, I built a test page to retrieve the value from local ...

Divs with floating left have a complete vertical border on their right side

I would like the first and second divs to have a full height border on their right side while floating left. CSS: div.wrapper { border: 1px solid black; } div.wrapper > div { text-align: center; width: 50px; padding-left: 5px; fl ...

Navigating the browser view across an extensive HTML page without relying on scrollbars

I have a large HTML page (approximately 7000x5000) and I need to be able to move the user's view around with JavaScript. Disabling the ability for the user to scroll by hiding the browser scrollbars using overflow:hidden on the HTML element is easy. ...

Spinning with animation in jQuery

Greetings! I am in the process of creating a popup box that will appear upon clicking the Login button. My aim is to produce a popup box with a rotating effect, however, my attempts have not been successful so far. You can view the code snippet on JsFidd ...

Dropdown with multiple selections organized in a hierarchical structure

I am in need of the following : Implement a drop-down menu that reflects hierarchical parent-child relationships. Include a checkbox for each node to allow for selection. If all child nodes are selected, their parent node should be automatically ch ...

Validation of Single Fields in Angular Reactive Forms

When I validate a reactive form in Angular, I expect the error message to show up beneath the invalid field whenever incorrect data is entered. <form (ngSubmit)=sendQuery() [formGroup]="form"> <div *ngFor='let key of modelKeys&ap ...

Adjusting the Transparency of the Background in a Pop-Up

I am experiencing an issue with my popup where I want the background to be transparent. However, when I set the opacity in CSS to 0.5 or less, the text also becomes transparent and very dark. How can I achieve a background with 50% opacity while keeping th ...

How can I ensure that the AppBar background color matches the color of the navigation bar?

Having trouble changing the background color of the <AppBar> in my project. Using the Container component to set a maximum screen size, but encountering issues when the screen exceeds this limit. The AppBar background color appears as expected while ...

Error message: "When namedPlaceHolder parameter is disabled, bind parameters must be in the form of an

Currently revamping my query due to a crucial API redesign. With the presence of a "file" as multipart/form-data, I found the need for a form handler since NextJS lacked one. After some workarounds with "multiparty", now I can successfully parse the incomi ...

What is the best way to add an Apple iPhone-like effect to a menu list?

I've been working on creating a menu similar to the Apple menu using the greensock api Here is my progress so far: JSFIDDLE Update This is what I am aiming for: Fiddle Any idea why there is flickering when hovering over it? <div class="de ...

The issue of border-radius and shadow box inconsistency

I'm trying to style a div with the following properties: .example { margin: 200px; width: 200px; height: 200px; border-radius: 20px; box-shadow: white 0px 0px 0pt 8pt, #033354 0px 0px 0pt 11pt; } <div class="example"> </div> ...

substitute a variable

I am trying to update the value of a variable using an HTML form. Within my config.php file, I have declared a variable $num = 3; I would like the value 3 to be replaced with whatever I input in the form form.html. Below is the code for my HTML form : ...