When the parent element has a fixed position, the child element will no longer maintain its floating property

I'm currently working on a fixed navigation panel that sticks in place while scrolling down. Here is the code I have so far:

<header>
    <a class="logo" href="/">Logo_name</a>
    <nav>
        <a href="#">Menu_1</a>
        <a href="#">Menu_2</a>
    </nav>
    <div style="clear: both;"></div>
</header>

Below is the corresponding CSS:

header {
    position: fixed;
    max-width:960px;
}

.logo {
    float: left;
}
nav {
    float: right;
}

My goal is to have the logo aligned to the left side and the navigation menus on the right side.

Currently, the floating seems to be working, but the nav elements are appearing right after the logo instead of being floated to the right edge.

When I remove the position:fixed property from the header, the floating works fine. Any suggestions on how to fix this issue would be greatly appreciated!

Answer №1

This is an alternative solution using flexbox instead of float:

header {
  width: 100%;
  max-width: 960px;
  display: flex;
  justify-content: space-between;
}

.logo {
  align-self: flex-start;
}

nav {
  align-self: flex-end;
}
<header>
  <a class="logo" href="/">Logo_name</a>
  <nav>
    <a href="#">Menu_1</a>
    <a href="#">Menu_2</a>
  </nav>
</header>

Additionally, remember to remove the clear: both; from the HTML code. Let me know if this solution works for you!

Answer №2

According to @AngelMdez, it is recommended to use Flexbox over Floats for better results. However, using position: fixed can still achieve the desired outcome as long as you specify a width for proper spacing.

Once the width is set, you can safely remove all instances of float and clear properties from your code.

body {
  margin: 0;
}

header {
  position: fixed;
  width: 100%;
  max-width: 960px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
  background-color: gray;
}

.content {
  padding-top: 70px;
}
<header>
  <a class="logo" href="/">Logo_name</a>
  <nav>
    <a href="#">Menu_1</a>
    <a href="#">Menu_2</a>
  </nav>
</header>

<div class="content">
  <p>
   // lorem ipsum content
  </p>
  // more lorem ipsum content
</div>

Original Example with Floats

header {
  position: fixed;
  width: 100%;
  max-width: 960px;
  background-color: lightgray;
  height: 60px;
}

.logo {
  float: left;
}

nav {
  float: right;
}
<header>
  <a class="logo" href="/">Logo_name</a>
  <nav>
    <a href="#">Menu_1</a>
    <a href="#">Menu_2</a>
  </nav>
  <div style="clear: both;"></div>
</header>

<div class="content">
  <p>
    // more lorem ipsum content
  </p>
  // even more lorem ipsum content
</div>

Answer №3

In response to your query: By default, most HTML elements come with styling provided by the browser known as the User Agent. The <header> element typically has a default value of display: block;, which means it expands to fill the available width within its container.

In this scenario, the container for the <header> is the <body>, whose width is determined by the <html> element that occupies the entire viewport.

When you set a max-width of 960px, the element will only grow to that specified width. However, when you apply an absolute positioning like `fixed`, the element is no longer part of the normal document flow. As a result, it loses the inherited width from its parent (the body) as there is no longer a defined width from a parent element.

To address the issue mentioned in your code snippet, simply add a width property to the element. Since you have already set a max-width: 960px;, you can make the element fill up 100% of the width using width: 100%;. This will ensure that the element stops expanding at 960px, which is the maximum width specified:

header {
  position: fixed;
  width: 100%;
  background: blue;
}

a {
  color: white;
}

.logo {
    float: left;
}
nav {
    float: right;
}
<header>
    <a class="logo" href="/">Logo_name</a>
    <nav>
        <a href="#">Menu_1</a>
        <a href="#">Menu_2</a>
    </nav>
    <div style="clear: both;"></div>
</header>

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

I am experiencing difficulties with my custom font not functioning properly

I've experimented with the following code: @font-face { font-family: Jua; src: url('/fonts/jua.ttf'); } @font-face { font-family: Jua; src: url('..../fonts/jua.ttf'); } @font-face { font-family: Jua; src: url('.../fonts/jua.t ...

Clear all CSS styles applied to a targeted division

My website built on Wordpress links to several CSS files. One specific div has its own unique style that is separate from the main Wordpress styles. Unfortunately, the Wordpress CSS ends up interfering with my custom div's layout. Is there a way in HT ...

Manipulating the DOM by linking to a div and using JSON information for opening and closing

I have retrieved data from a JSON file and displayed it as a link. I am looking to implement functionality that allows me to hide and show a div when the link is clicked. Below is the code I'm currently using: $(document).ready(function() { $ ...

When there is an absence of data, the jQuery datatable mysteriously van

I have encountered an issue in my Django app where a datatable used in the template disappears if there is missing data in any column or row. The problem occurs when trying to download the data in CSV, Excel, PDF, or copy format. Here is the HTML code snip ...

How Webpack 4 Utilizes splitChunks to Create Numerous CSS Files

I need to create multiple CSS files using webpack 4 with the min-css-extract-plugin and splitChunks plugin. Here is my webpack configuration. const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const path = require("path"); module.exports = ...

Problem with Bootstrap 3 navbar on mobile devices - not tappable or responsive

After years of using Bootstrap, I've come across a new issue with my implementation of a Bootstrap 3 Nav. While testing on a desktop browser with device emulation, the nav collapses and functions properly. However, when tapping on the header on an ac ...

Improving the Performance of HTML/CSS Animations - Enhanced Animation Speed

I have created an HTML page with CSS animation and transitions. <div class="container-fluid" id="team"> <div class="row first"> <div class="wrapper"></div> </div> <div class="row second"> <div class="wrapper" ...

Struggling to Position Advertisement in CSS

I've been struggling to properly center a div using CSS. Adding text-align: center; doesn't seem to do the trick. The issue can be found in the top advert on this website: . Do you have any suggestions? Here's some sample code: HTML: &l ...

Obtain the CSRF token from a webpage using JavaScript

I am currently working on a project where I need to retrieve the csrf token from a web page built with Django using javascript. The structure of my HTML template is as follows: <div class = "debugging"> <p id = "csrf">{% csrf_token %}</p ...

Utilize a Dropdown Menu to Retrieve Information from a Database and Display the Results on Either the Current Page or a Separate Page

My PHP page includes a code snippet that generates an HTML table: <table> <thead> <tr> <th class="wheniwant">Date</th> <th class="wheniwant">Income Amount</th> <t ...

The Elusive Key to Perfect Layouts and its Transformation

Today I discovered the Holy Grail of Layouts while coding, but when I implemented it, the output in browsers was not as expected. The borders were incomplete and strange: Here is the code snippet that caused the issue: #container { border: 10px soli ...

Middleware that handles form post requests quickly became overwhelmed and resulted in a RangeError

Currently, I am working with a form using ejs templates to collect data. When accessing the "/" route, my application renders the "main" view and utilizes a middleware to handle the form data. However, I encountered an error stating "RangeError: Maximum ca ...

How to Use Jquery to Delete a Specific String

I've been attempting to remove certain strings from a string using Jquery, however it seems like the code isn't working and my variable remains unchanged. var classes = $("body").attr('class'); alert('.side-nav' + classes); c ...

What is the best way to extract the body content from a Markdown file that includes Frontmatter

How can I retrieve the content of the body from my markdown file using front matter? Currently, it is displaying as undefined. What steps should I take to fix this issue? {latest.map(({ url, frontmatter }) => ( <PostCard url={url} content={frontmat ...

I have implemented a button in PHP and now I am looking to invoke a function when that button is clicked

I have a PHP-generated HTML button and I'm having trouble calling the mybtn3() function when it is clicked. The button code looks like this: echo"<td width=14% align=center><input type=button value=Export onclick=mybtn3() /></td>"; ...

What is the best way to pass the reference of the p tag every time the button is clicked?

This is the code I used to create a button: <button type="submit" id="likebtn" onclick="likedpost(this) " data-postid="<%=blog._id%>" data-author="<%=user.username%>">Like</button> ...

Unable to make a div grow within a Popper component in a React.js application

I'm facing a challenge with implementing a CSS feature and need some assistance. https://i.stack.imgur.com/KXpGd.png Upon clicking the "See link options" button, the content loads but spills out of the popper. My goal is to have the popper expand in ...

"Using jQuery to trigger a click function on elements with the same

Whenever I click the comment link all of the divs are opening but i need that particular only to be opened. HTML: <div> <a href="#" class="ck">comment</a> <div class="cmt"> <input type="text" class="txt"/> ...

Having trouble getting the overflow scrollbar to work properly?

I recently created a Whiteboard using Vue. The Whiteboard consists of an SVG element where I can add other SVG elements like paths to it. In order to enable scrolling within the SVG, I came across this example which seemed quite helpful. Check out the exa ...

Changing the color of Material UI pagination: a step-by-step guide

I have integrated Material UI to create a pagination bar for my website. While everything is functioning properly, I am looking to personalize the appearance. After reviewing their documentation, I tried implementing a theme but encountered an issue with c ...