Questions surrounding the proper placement of a div within a relative element

I am currently learning how to create a web template without using tables, using HTML and CSS. I have some questions regarding the positioning of elements in my template.

Here is an image of how my final template should look:

Next, I need to position the horizontal main menu (the green one inside the header).

The tutorial suggests using absolute positioning to move the nav div containing the navigation menu to the right.

To achieve this, the tutorial recommends the following steps:

  1. Set the position of the parent div as relative and specify the exact height of this parent div
  2. Use absolute positioning for the nav div

Therefore, for my template, the HTML code should look something like this:

        <div id="header">    <!-- HEADER -->
            <div id="logo">     <!-- My Logo -->
                <h1><a href="#">My website</a></h1>
                <p id="slogan">
                    Welcome to my website
                </p>
            </div>

            <div id="nav">
                <ul>
                    <li>
                        <a href="#">Home</a>
                    </li>
                    <li>
                        <a href="#">Portfolio</a>
                    </li>
                    <li>
                        <a href="#">Blog</a>
                    </li>
                    <li>
                        <a href="#">Contact</a>
                    </li>
                    <li>
                        <a href="#">About</a>
                    </li>
                </ul>
            </div>

And here is how the CSS code would look:

#header {
    background: #092F85;
    position: relative;
    height: 193px;          
}   

#nav{
    background: #93D459;
    position: absolute;
    top: 166px;
    right: 0;
}

I believe that understanding the positioning of the #nav div is straightforward (please correct me if I'm mistaken). It seems to be positioned absolutely on the right side and pushed down by 166px.

What confuses me is why the position of the parent div (#header) needs to be set as relative?

In general, when using position: absolute, the parent element is often specified as position: relative. But what does this mean exactly?

Thanks,

Andrea

Answer №1

When applying the CSS rule position: absolute to an element, it will be positioned relative to the <body> element. However, if you use position: relative on a parent element further down the DOM hierarchy, the positioning will be based on that parent element instead. Let's take a look at the following example:

#positioned_element
{
    position:absolute;
    top: 10px;
}

<body>
    <div id="container">
        <div id="positioned_element">
        </div>
    </div>
</body>

In this scenario, there will be a gap of 10px between the beginning of the body element and the #positioned_element. However, if we modify the CSS like so:

#container
{
    position: relative;
}

#positioned_element
{
    position:absolute;
    top: 10px;
}

The 10px gap will now be between the top of the #container element rather than starting from the body element. This is because the absolutely positioned element is now relative to the #container element.

Additionally, it may be beneficial to consider using float: right in some cases as well.

Answer №2

When an element, such as your #nav element, is given a position:absolute, it will be positioned in relation to its closest ancestor that has a position:absolute, position:relative, or position:fixed. If none of its ancestors have any of these position values, then it will be positioned relative to the initial containing block (refer to @Alohci’s comment below).

To ensure that #nav positions itself in relation to #header, you need to give #header a position:relative.

You could alternatively give #header a position:absolute or position:fixed, but this would cause it to no longer take up layout space in the document, resulting in subsequent elements moving up.

Answer №3

You may want to enhance your understanding of css and how to utilize position: absolute

This article provides a good explanation: http://example.com/css-tricks-absolute-positioning

(It's important to note that in Web Development, there are often multiple approaches to achieve the same result.)

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

Analyze HTML while maintaining the integrity of the initial content

I am facing a challenge with my HTML files. I need to replace certain elements while leaving the rest of the content untouched. Specifically, I am looking to run this jQuery expression (or something similar to it): $('.header .title').text(&apos ...

What is the best way to adjust the size of my <div> to accommodate additional vertical content?

Every time I attempt to include margin-top: 30px to my box_1 and box_2 <div>, the bottom <div> is pushed down and disappears. It seems like my wrapper isn't expanding to accommodate the content. How can I achieve a 30px space between the ...

"Vanishing act: The mystery of the disappearing Bootstrap dropdown

I am currently using Bootstrap 3 in conjunction with Ruby on Rails through the Rails Tutorial Sample App. Within my application, users have the ability to like, or "savor," microposts, referred to as "pops." My goal is to display Gravatar icons of users wh ...

Combining Text in HTML Using CSS to Create Layered Effects

Link to GitHub: http://github.com/user123/code I'm attempting to position "welcome" behind "home", but I've been struggling to achieve this. I've experimented with setting the position, but so far I haven't been successful. Here' ...

Is it possible to conceal any spans that are in close proximity to the cursor when hovered over?

Currently, I am working on a project that involves multiple spans placed side by side, with each span containing a letter of the text. My aim is to create a functionality where hovering over one of these spans will not only hide that particular span but al ...

Eliminating a pattern with underscore.js or jquery - the complete guide

I am looking to remove the ellipses (...) from a value such as ...India. How can I achieve this using underscore.js, jQuery, or JavaScript? Any tips on how to accomplish this would be greatly appreciated! ...

Select a specific date range from a form and export CSV file containing MySQL data within that range

I have successfully implemented a database CSV export functionality, but now I am looking to allow the user to specify a date range for the export process. Below is the HTML section that handles the date selection (date format: mm/dd/yyyy): <form act ...

creating hidden and displayed forms using php

I am in need of a hidden form that only becomes visible after the user clicks a button. Once the submit button is pressed, the form should return to its invisible state. Does anyone have any suggestions on how to achieve this functionality? I believe it m ...

Include an additional feature to an already established design

I have been attempting to move an element to the left using the transform property. However, there is already a pre-existing style with transform, which appears as: transform: translate3d(tx, ty, tz) What I am aiming for is to incorporate another property ...

Incorporate a background image into input fields with Autofill on mobile browsers to override the default yellow background that obscures them

It is common knowledge that modern browsers apply a less than appealing yellow background to text fields when Autofill is used by visitors. A helpful workaround is known to override the default text and background colors, and even incorporate a background ...

Having trouble incorporating autocomplete search results into an HTML table using Jquery, Ajax, and JSP

My current project involves an App that utilizes AJAX with jQuery to communicate with a Spring-boot REST controller. While the app is functional, I am facing difficulty in displaying the search results neatly within HTML tables. https://i.sstatic.net/7sw8 ...

What is the best way to align an Icon in the navbar-toggler of Bootstrap 5?

When working with Angular and Bootstrap to develop a navigation bar, I encountered an issue with aligning a user icon in the navbar. The picture below shows the problem that arises when trying to center align the user icon among other links in the navbar. ...

Issues arise when attempting to create smooth animations with 100% transform translate across different web browsers

After uncovering an ancient piece of JS code that I had once shared for free use, I discovered that a CSS animation bug from 3 years ago is still causing trouble today. The issue involves animating an element from left:100%/transform: translateX(100%) or ...

What is the best way to test the output of HTML code in a unit test scenario

I am new to web development and testing, taking it slow. I have a website with a button that reveals information when clicked. How can I create a test case to ensure that the displayed output is correct? I need to verify that the text appears on the scre ...

Perform a function dynamically once a specific textfield is filled and continuously while filling another textfield

Imagine we have two text fields - one for a first name and one for a surname. As I type in the surname field after already filling out the first name, a function called sug() should provide suggestions or perform some action each time I add another letter ...

Alter the navigation background when moving between sections on a one-page website

I need to ensure that the background of the navigation remains transparent on the "home" section. However, when switching to other sections, the background color of the navigation becomes permanently black. <header class="clearfix"> <nav> ...

Matching Javascript Variables to CSS Styles

I am currently developing a small HTML page and I am utilizing JavaScript to retrieve the screen dimensions. However, I am facing an issue with passing this variable to a CSS style as shown below. How can I achieve this successfully? Additionally, I have ...

php - assign image to picture through file location

My webpage features an img element with the following code: <img id=".."class=".." src="setPhoto/second_photo.php"> In the source attribute, I have linked to a .php file: <?php $id = $_SESSION['u_id']; $sql = "SELECT * FROM users WHER ...

The implementation of jQuery within an included HTML file may not function properly

I'm looking to implement the use of includes for generic HTML elements in my project. However, I've run into an issue where including an HTML file causes jQuery to stop working. Here is a snippet of my code that illustrates the problem. Specifica ...

The issue of conflicting stylesheets is causing alignment and height discrepancies when using multiple icons

Is there a way to align icons from different stylesheets to have the same height? When attempting to use icons from separate stylesheets, I encountered a height issue where one icon left space at the top and bottom while another appeared correctly aligned. ...