The text I have written is appearing below my Bootstrap navigation bar

I am currently working on a React project to create a simple landing site with multiple pages. After successfully setting up the routes to navigate between pages, I encountered an issue while designing the home page. The text I added seems to be overlapping with the navigation bar, and I am struggling to position it below the navbar.

Home:

import React, {Component} from 'react';

    class Home extends Component {
        render(){
            return (
                <div>
                    <div>
                        <section>
                            Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                       </section>
                  </div>
              </div>
           );
         }
      }

export default Home;

Nav:

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Home from './Home';
import About from './About';
import Contact from './Contact';

class Nav extends Component {
    render(){
        return (
            <Router>
                <div>
                    <nav class="navbar fixed-top navbar-expand-sm navbar-light bg-light">
                        <a class="navbar-brand" href="#">Movie Garden</a>
                        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                            <span class="navbar-toggler-icon"></span>
                        </button>
                        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
                            <div class="navbar-nav ml-auto">
                                <Link to={'/'} class="nav-link active">
                                Home
                                </Link>
                                <Link to={'/about'} class="nav-link">
                                About
                                </Link>
                                <Link to={'/contact'} class="nav-link">
                                Contact
                                </Link>
                            </div>
                        </div>
                    </nav>
                    <Switch>
                        <Route exact path='/' component={Home} />
                        <Route path='/contact' component={Contact} />
                        <Route path='/about' component={About} />
                    </Switch>
                </div>
            </Router>
        )
    }
}

export default Nav;

Bootstrap is the only framework being used at the moment.

Answer №1

It appears that the issue is caused by using the fixed-top class name on your navbar. This class applies fixed positioning to the element, which removes it from the normal flow of the DOM. As a result, when the navbar is detached from its usual position in the DOM structure, the surrounding <section> is pushed up because the navbar no longer affects the layout of the containing div.

To address this problem, I recommend the following solution:

<div className="route-outlet">
  <Switch>
      <Route exact path='/' component={Home} />
      <Route path='/contact' component={Contact} />
      <Route path='/about' component={About} />
  </Switch>
</div>

Enclose the <Switch> component within a wrapping <div> that will act as the container for all route outlets. Here is the CSS style you can apply to this wrapping <div>:

.route-outlet {
  padding-top: headerHeight; // Specify your header height here
}

By adding a padding-top, the content will be correctly positioned below the navbar. While you could use margin-top instead, I recommend sticking with padding-top due to potential issues with margin-top behavior.

In summary:

Utilizing a wrapper <div> eliminates the need to individually style every page with padding-top. This approach ensures that all pages rendered through the Switch component will automatically have their content positioned appropriately.

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

In the world of RTK Query, the eslint tool raises alarms with the @typescript-eslint/no-invalid-void-type error when a query's parameter is

My query function is missing a parameter. endpoints: (build) => ({ fetchEvents: build.query<Test[], void>({ query: () => '/test' }), }) ES-Lint errors: void should only be used as a return type or generic type arg ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

"Discover a unique online platform showcasing videos and images with a creative

I recently updated my personal website to showcase some of the tools I've developed through short looping videos. Initially, everything was working well with just images, but when I switched to videos, I encountered some unexpected behaviors. Interest ...

Exploring the implementation of float type in TypeScript

Is it possible to use Number, or is there a more type-specific alternative? In the past, I have relied on Number and it has proven effective for me. For example, when defining a variable like percent:Number = 1.01... ...

Is the table column width not aligning with the grid container width in bootstrap?

I've been grappling with trying to construct a table using Bootstrap 4 grid container. While everything from styling to alignment seems to be in place, there's one nagging issue: the table doesn't adhere to the grid container as anticipated. ...

Troubleshooting issues with the Select List component in ReactJS

Having an issue with the select list as the onChange event is not triggering. Struggling to set the selected value from the list in the this.state variable. Any assistance on this matter would be greatly appreciated. class SelectActivity extends React.C ...

I'm stumped on how to fix the error with the Datepicker - any suggestions on what my next

import { useField } from "formik"; import { Form, Label} from "semantic-ui-react"; import DatePicker, {DatePickerProps} from 'react-datepicker'; export default function CustomDateInput(props: Partial<DatePickerProps>) { ...

Make Changes to Files Post-Build in React

I created a React app using create-react-app, utilizing JavaScript, CSS, HTML, and React. After running npm build, I deployed the app on Netlify. Now, I need to make some CSS adjustments. So, I navigate to the project directory on my laptop and run it loc ...

React failing to acknowledge messages from socket.io server

Currently, I am diving into the world of WebSockets and Socket.io. To assist with my learning process, I have created a basic text field along with a button on my frontend code: import React, { Component } from 'react' import './App.css&apos ...

Modifying a particular value in React using useState

const [selectedHealth, setSelectedHealth] = useState(checkboxHealthLabels); const updateSelectedHealth = (event) => { setSelectedHealth([ ...selectedHealth, { [event.target.name]: event.target.checked }, ]); }; and checkboxHealthLabels data : exp ...

Developing a custom CSS for React using clamp and focus attributes

I'm currently working on creating an object to be used in inline style, but I'm having trouble figuring out how to correctly write `clamp` and `after`. const PhoneInputStyle = { fontSize: clamp("13px", "1.111vw", "16px"), /*this particular ...

When inline-block elements wrap onto a new line, they expand to full width

Upon my realization, an inline-block element will expand to 100% width if there are more child elements than can fit on one line: <div style="background-color:red;padding:5px"> <div style="display:inline-block;background-color:green;padding:5 ...

The Script Component is not functioning properly in next.js

While using Tiny Editor, I encountered an issue with defining a key for the editor. According to the documentation, I need to access this key through the tag <script src='address'. This method seems to work fine initially. However, when combin ...

Expanding the ul height with animation when the page loads

Hi there, I am a beginner looking to create a ul list that increases its height with animation when the page loads. Can this be achieved with CSS? Any assistance would be greatly appreciated. <ul> <li><a href="/">title 1</a>& ...

Avoid making preflight requests when making axios.post calls

My micro-service is built with spring-boot and spring security, while the frontend is created using react-hooks. However, when I try to send data to my micro-service using the axios.post method, it initiates a CORS preflight request (options method) becaus ...

Switch Tabs with Dropdown Selection

I came across a website with a similar feature, but I am interested in using a dropdown menu instead of a button or link. Check out this webpage for reference The problem seems to be related to this line of code: onchange="$('#'+$this).tri ...

Issue with jQuery DataTables column.width setting failing to meet expectations

Currently, I am utilizing datatables for my project. According to the datatables documentation found here, it suggests using the columns.width option to manage column width. However, when I implement columns.width and render the table, it seems to disreg ...

Can Python be used to determine if a website is responsive?

I am currently utilizing Python3 alongside BeautifulSoup. I am interested in determining whether a website is responsive or not. Initially, I considered checking the meta tags of a website to see if it contains something like this: content="width=device- ...

Apply a CSS class to the header cells

I'm facing a challenge with adding a CssClass to a table that is generated automatically through C#. The table creation code looks like this: TableHeaderRow header = new TableHeaderRow(); cell1 = new TableCell { Text = "Brand" }; cell2 = new TableCel ...

Avoid multiple callings of dataLabels formatter while using Highcharts columnrange chart

My datetime chart is designed to display time intervals. I want to add labels to each interval that show data from the array passed to the chart. However, I am encountering issues as the number of elements in the array increases. The datalabels are overlap ...