Issue with margin-top not functioning correctly when utilizing position: fixed via JavaScript

When the navbar is in a fixed position, the margin top of the logo doesn't work correctly. The attached image shows that when scrolling down, it disappears https://i.sstatic.net/JNog6.jpghttps://i.sstatic.net/S5AJ5.jpg

<div class="container">
    <div class="row number">
        <div class="col-sm-5 col-xs-3">

        </div>
        <div class="col-sm-2 col-xs-2">
        </div>
        <div class="col-sm-5 col-xs-7">
            <h2>Call Us Today<br>
            <a href="tel:+1-778-233-0368">604-729-3864</a></h2>
        </div>
    </div>
</div>
<nav class="navbar navbar-inverse" role="banner">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>

            </button>
            <nav>
            <%= link_to root_path do %><%= image_tag "plumbertodaylogo.png",alt: "plumber-today-logo",class: "logo"%><% end %>
            </nav>
        </div>

        <div class="collapse navbar-collapse navbar-right">
            <ul class="nav navbar-nav">
                <li class="active"><%= link_to "Home", root_path %></li>
                <li><%= link_to "About Us",about_path %></li>

                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Plumbing <i class="fa fa-angle-down"></i></a>
                    <ul class="dropdown-menu">
                        <li><a href="blog-item.html">Repipe/ Burst pipes</a></li>
                        <li><a href="pricing.html">Leak Detection</a></li>
                        <li><a href="404.html">Fixture repair & Installation</a></li>
                        <li><a href="shortcodes.html">Garbage Disposal Services</a></li>
                        <li><a href="shortcodes.html">Hot Later Tanks</a></li>
                        <li><a href="shortcodes.html">Watermains</a></li>
                        <li><a href="shortcodes.html">Sump & Pump services</a></li>
                    </ul>
                </li>

                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Drainage <i class="fa fa-angle-down"></i></a>
                    <ul class="dropdown-menu">
                        <li><a href="blog-item.html">Drain cleaning pipes</a></li>
                        <li><a href="pricing.html">Sewer Main</a></li>
                        <li><a href="404.html">Clogged toilet Services</a></li>
                        <li><a href="shortcodes.html">Draintile Services</a></li>
                        <li><a href="shortcodes.html">Camera Inspection</a></li>
                        <li><a href="shortcodes.html">Hydrojetting</a></li>
                    </ul>
                </li>

                <li><a href="portfolio.html">Service Areas</a></li>
                <li><a href="blog.html">Reviews</a></li> 
                <li><a href="blog.html">Blog</a></li> 
                <li><a href="coupons.html">coupons</a></li> 
                <li><%= link_to "Contact" ,new_contact_path %></li>                        
            </ul>
        </div>
    </div><!--/.container-->
</nav><!--/nav-->

Javascript file

$(window).scroll(function(e){ 
  var $el = $('.navbar'); 
  var isPositionFixed = ($el.css('position') == 'fixed');
  if ($(this).scrollTop() > 200 && !isPositionFixed){ 
    $el.css({'position': 'fixed', 'top': '0px'}); 
        $('.logo').css({'margin-top': '-10px','width': '10px'});

  }
  if ($(this).scrollTop() < 200 && isPositionFixed){
    $el.css({'position': 'static', 'top': '0px'});
        $('.logo').css({'margin-top': '-110px','width': '150px'});

  } 
});

CSS

.navbar {
  border-radius: 0;
  margin-bottom: 0;
  background: white;
  padding: 0px 0;
  padding-bottom: 0;
  position: fixed;
  z-index: 100;
  width:100%;
}

 .logo{
  margin-top: -110px;
  width: 150px;
 }

Answer №1

When applying the position: fixed property, remember to utilize top: 50px instead of margin-top: 50px. This is because the fixed position is in relation to the screen, not the parent div.

Given that the navbar is set to fixed, there are no elements above the image causing it to move upward. To account for this movement, you should adjust the image's positioning by adding the combined values of the height of the fixed navbar and the margin top.

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

Ways to enlarge the parent container and reveal a concealed child element upon hovering without impacting neighboring containers

Currently, I am diligently working on the company service boxes and have a particular need... When hovering over: 1. The parent div should scale up and acquire box shadow without impacting the neighboring service boxes (it should appear to stand out above ...

Adjust the text color based on the background image or color

Here on this site, I have designed the first div to display a dark image, while the second one shows a light background. I am aiming to adjust the sidebar text color based on whether it is displayed against the dark or light background. How can I achieve ...

Styling the time ticks on the x-axis in Nivo Line Charts

I need help styling the x-axis of my line chart to show time. I am utilizing the @nivo/line react library for generating charts. axisBottom={{ tickValues: 3, tickRotation: 90, format: (values) => `${getRequiredDateFormat(values, 'MMMM-DD ...

Customizing Angular 2's Webpack environment setup dynamically

Currently, I have set up Webpack to compile my Angular project. Within my project, there is an important file called env.js: module.exports.ENV = { API_URL: "http://localhost:5001/", ... }; In the webpack.common.js file, I am referencing this file l ...

JavaScript array containing objects remains static

I'm facing an issue with a complex array of objects (I will only display the necessary nodes to explain the problem): var arr = [ { json: { doc: { id: 1, atualizacao:{ ...

Transforming JSON data into comma-delimited values (with thousands separators) using Angular 5 and ES6 syntax

Is there a more elegant method to convert a JSON response into comma-separated numbers for displaying currency purposes? Here is the code I have currently: let data = { "business":{ "trasactionTableData":[ { ...

Creating dynamic selection options in an HTML select tag using PHP

When retrieving category and sub-category information from an API json file, the API returns category objects with a "parent" attribute. Main category objects have a parent attribute equal to 0, and sub-category objects have the parent attribute equal to t ...

Adding properties to a class object in Javascript that are integral to the class

Recently, I've been contemplating the feasibility of achieving a certain task in JavaScript. Given my limited experience in the realm of JavaScript, I appreciate your patience as I navigate through this. To illustrate what I am aiming for, here' ...

Modify the index in the creation of a json

I am trying to create a JSON object using the code below: var myJSONObject = []; var id = "1", value = "I'm a value !"; myJSONObject.push({id:value}); When I display this construction, it shows: [{"id":"I'm a value !"}] However, I want it to d ...

Having trouble loading a local texture in Three.js while using it as a component in Vue.js

When I run a three.js animation as a component within Vue, it works perfectly fine when loading the texture from an external online resource. However, when I try to run it locally by loading the texture from a local path, it displays black with no error me ...

Tips for combining or adding duplicated values in a Javascript array

I am facing a problem with an array object that looks like this: [ {"item_id":1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000}, {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"origin ...

Generating and saving a text file in a React Native application

Is there a way to convert a string into a text file within the client application and then download it directly onto a phone? If so, how can this be achieved? ...

Navigating Next.js: Mastering the art of localStorage Access

Currently, I am developing my first member area using next.js. My goal is to store some data in localStorage (such as token, expiresAt, userInfo), which will eventually be moved to an http-only cookie. The code below is generating the error: "LocalStorage ...

Ways to expand the height of content using grid?

I'm having trouble getting my grid template to stretch content to the end using CSS Grid. The behavior is unexpected, and I want to create a Jeopardy game where clicking on a box reveals a question. Initially, I applied display: grid to the body elem ...

Access-Control-Allow-Origin does not permit the origin null

I've been searching for an answer to this question, but I haven't found a suitable one yet. let xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && xhr.status === 200){ let response = r ...

Is there a way to customize my visual studio code to automatically insert an indented space between curly brackets in CSS when I press enter?

Whenever I try to open curly brackets in CSS and press enter, it simply moves to the next line without adding an indentation as shown below: body { } Despite going through the settings and experimenting with different options, I haven't been able to ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

Troubleshooting MaterialUI Datatable in Reactjs: How to Fix the Refresh Issue

Currently, I am facing an issue with rendering a DataTable component. The problem is that when I click on the "Users" button, it should display a table of Users, and when I click on the "Devices" button, it should show a table of Devices. But inexplicably, ...

What could be the reason for my failing express test?

I'm in the process of configuring a server using Node/Express and I want to write ES6 code, so I've incorporated babel into my setup. Currently, the server is operational, and I can successfully make the necessary requests. However, I am facing ...

Error: Ajax unable to parse JSON - property 'name' does not exist in the object

When accessing my report.php file, it returns a json data. Here is the snippet of javascript code I am using to try and read the json: <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script> $(document).ready(function ...