How to center an HTML header

Currently working on a one-page scrollable website, aiming to have the first page consist of a navbar, image, and header. The challenge I'm facing is centered around aligning the header vertically. Although I managed to center it horizontally, the vertical alignment eludes me. Hoping for some assistance in identifying the issue as I've been grappling with this frustrating problem for hours.

You can get an idea of what I'm trying to achieve by referring to:

Below is the code snippet:


/*body {
    background: linear-gradient(rgba(#F9774C, .75), rgba(#802A0C, .85));
    background-image: url("Background_photo_2.jpg");
    background-size: cover;
    box-shadow: 4056 3000px rgba(0, 0, 0, 0) inset;
      /* Center and scale the image nicely 
    background-position: center;
    background-repeat: no-repeat;
    height: 50%;
            }*/ 

nav {
    font-size: medium;
}

.nav-item a{
    color: white !important
}

 body, html {
    height: 100%;
    margin: 0;
    padding: 0;
    font-family: 'Montserrat', sans-serif;
 }

/*styles background image*/
.bg-img {
    height: 100%;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    box-shadow: 4000px 3000px rgba(0, 0, 0, 0.6) inset;      
}          

/* use this to change the general fonts */
p, h1 {
    color: white;
}

/* arranges navbar items to right */
ul {
    margin-left: auto;
}

.bg-img.container {
    display: flex;
    justify-content: center;
    align-items: center;
}
#content {
    width: 100%;
    height: 85%;
    display: flex;
    justify-content: center;
    align-items: center;
}
/*.container-fluid {
    width: 70%;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Home - Both Sides Now </title>
  <!-- BOOTSTRAP CDN IMPLEMENTATION-->

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!-- Links to the stylesheet-->
  <link rel="stylesheet" type="text/css" href="style.css">

  <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
</head>

<body>
  <div class="bg-img">
    <!--This is the navbar-->
    <div class="container col-md-10">
      <nav class="navbar transparant navbar-expand-lg navbar-dark">
        <a class="navbar-brand" href="index.html"><img src="logotransparant.gif" class="d-inline-block align-top" width="60" height="60"></a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
          <ul class="navbar-nav">
            <li class="nav-item active">
              <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Features</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#">Pricing</a>
            </li>
          </ul>
        </div>
      </nav>

    </div>

    <header class="masthead d-flex h-100 justify-content-center">
      <div class="container ">
        <div class="mx-auto text-center">
          <h1 class="mx-auto my-0 text-uppercase">Grayscale</h1>
          <h2 class="text-white-50 mx-auto mt-2 mb-5">A free, responsive, one page Bootstrap theme created by Start Bootstrap.</h2>
          <a href="#about" class="btn btn-primary js-scroll-trigger">Get Started</a>
        </div>
      </div>
    </header>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</div>

</html>

Answer №1

nav {
            font-size: medium;
        }
        
        .nav-item a {
            color: white !important
        }
        
        body,
        html {
            height: 100%;
            margin: 0;
            padding: 0;
            font-family: 'Montserrat', sans-serif;
        }
        /*styles background image*/
        
        .bg-img {
            /*background-image: url("Background_photo_2.jpg");*/
            height: 100%;
            background-position: center;
            background-repeat: no-repeat;
            background-size: cover;
            box-shadow: 4000px 3000px rgba(0, 0, 0, 0.6) inset;
        }
        /* use this to change the general fonts */
        
        p,
        h1 {
            color: white;
        }
        /* arranges navbar items to right */
        
        ul {
            margin-left: auto;
        }
        
        .bg-img.container {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        #content {
            width: 100%;
            height: 85%;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        /*.container-fluid {
        width: 70%;
    } */
        
        .mx-auto {
            position: absolute;
            top: 50%;
            left: 50%;
            -webkit-transform: translate(-50%, -50%);
            -moz-transform: translate(-50%, -50%);
            transform: translate(-50%, -50%);
        }
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home - Both Sides Now </title>
    <!-- BOOTSTRAP CDN IMPLEMENTATION-->

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <!-- Links to the stylesheet-->
    <link rel="stylesheet" type="text/css" href="style.css">

    <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet">
</head>

<body>
    <div class="bg-img">
        <!--This is the navbar-->
        <div class="container col-md-10">
            <nav class="navbar transparant navbar-expand-lg navbar-dark">
                <a class="navbar-brand" href="index.html"><img src="logotransparant.gif" class="d-inline-block align-top" width="60" height="60"></a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav">
                        <li class="nav-item active">
                            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#">Features</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="#">Pricing</a>
                        </li>
                    </ul>
                </div>
            </nav>

        </div>

        <header class="masthead d-flex h-100 justify-content-center">
            <div class="container">
                <div class="mx-auto text-center">
                    <h1 class="my-0 text-uppercase">Grayscale</h1>
                    <h2 class="text-white-50 mt-2 mb-5">A free, responsive, one page Bootstrap theme created by Start Bootstrap.</h2>
                    <a href="#about" class="btn btn-primary js-scroll-trigger">Get Started</a>
                </div>
            </div>
        </header>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</div>

</html>

Answer №2

Avoid the hassle of using styles by letting Bootstrap handle it for you:


<header class="row align-items-center masthead d-flex h-100 justify-content-center">
  <div class="container ">
    <div class="mx-auto text-center">
      <h1 class="mx-auto my-0 text-uppercase">Grayscale</h1>
      <h2 class="text-white-50 mx-auto mt-2 mb-5">A free, responsive, one page Bootstrap theme created by Start Bootstrap.</h2>
      <a href="#about" class="btn btn-primary js-scroll-trigger">Get Started</a>
    </div>
  </div>
</header>

Enhance the header div by adding two additional classes.

Tip: You may need to include the col class in your content elements after adding the row class.

Answer №3

There are two ways to vertically center:

  • To align the navigation bar, remove it from flexbox calculations by adjusting your code.

  • To exclude the height of the navigation bar from the page, calculate its height (86px) and subtract it (172px) from the total height.

It's up to you to decide which method works best, but in my opinion, the first option is preferable.


1st Approach

Add align-items-center vh-100 to the masthead class attribute and apply the following CSS:

.bg-img > .container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
}
...

2nd Approach

Add align-items-center to the masthead class attribute and use this CSS rule:

.masthead {
    height: calc(100vh - 172px);
}
...

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

How can I connect the playback speed of an HTML5 video element with Vue.js?

Is it possible to bind the playbackRate of an HTML5 video element without using getElementById in Vue.js? //Example of directly manipulating playbackRate with plain javascript var vid = document.getElementById("myVideo"); vid.playbackRate = 0.5; ...

Press on the menu <li> item to create additional submenus

A group of friends is facing a challenge. They want to create a dropdown sub-menu that appears directly below the selected item when clicking on a link from a menu. So far, they have been able to use ajax to send requests and generate a sub-menu. However, ...

obtain the string representation of the decimal HTML entity value

Similar Question: how to create iphone apps similar to ibeer, imilk, ibug, ibeer Using javascript to obtain raw html code Imagine having an html section like this: <div id="post_content"> <span>&#9654;<span> </div> ...

Add a css class to a <div> that is created by an <ng-template> inside the <ngx-datatable-column> element

I am struggling to implement the display: flex style on the parent <div> containing my <span> However, since the <span> is dynamically generated by the ng-template of the ngx-datatable-column, I'm finding it challenging to apply thi ...

transferring the parsed JSON document to the recipient, however, it does not adhere to

After calling the API and parsing the JSON data, I now aim to present this parsed JSON in tabular form on the receiving page. Currently, it is being displayed as plain text. The API URL used for testing purposes has been sourced from WIKI to safeguard act ...

Calculate the total width of LI elements and apply it to the parent UL or DIV

Is there a way to calculate the Total LI width and then set the width for the parent div? Here is an example of my code: <ul> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds&l ...

Adjusting the size of <nav> element to accommodate its child elements

I've exhausted all possible CSS solutions today in an attempt to make my parent nav tag home-main-nav-menu resize based on its children and grandchildren, but it just won't cooperate. If anyone could provide a clear explanation on how to solve th ...

PHP encountered an issue while trying to compare the value stored in the $_POST variable with the value stored in a

In my current project, I have utilized a JSON file to store data and PHP to retrieve and display it. However, I am facing an issue when comparing values from $_POST - specifically, if the value contains spaces, the comparison fails. Here is the problematic ...

Encountering an issue stating "The element is not visible at the moment, therefore cannot be interacted with" while trying to access a text box within a window opened via an ajax call

Currently, I am working on a Selenium script using Java to automate a specific process. However, I have encountered an issue where clicking on a dropdown causes a hidden popup to appear through an ajax call. Unfortunately, when attempting to interact with ...

What's the best way to target an element that is outside a certain parent container, but based on the parent's class?

Looking to target specific divs with a data-role of content that are not nested within a data-role="page" div with the class "modal". Advanced CSS selectors are not my forte. <div> <div data-role="page"> <div data-role="content" ...

I'm looking for a method to retrieve the value of an option tag and then pass it to a helper within handlebars. Can someone

Currently, I am utilizing express and handlebars in my project. I have a specific view where I aim to display certain information based on the event when a client selects an option from a select tag. However, I have some queries regarding this: Is it fea ...

Received a notification after submitting an HTML form

<html> <body> <form action="" method="GET> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> <?php if( $ ...

How to display umlauts (åäö) using Verdana font in Internet Explorer versions 8 and 9

Encountering a strange issue on certain pages where the rendering of umlauts (åäö) appears incorrect in IE8 and IE9 at times. The encoding is utf-8 (and most of the site functions correctly, so I know it's correct). I have attempted to isolate the ...

Conflicts in SwiperJS Timeline Management

Having a Timeline on my Website using SwiperJS presents challenges with conflicting functions. The goal is to navigate swiper-slides by clicking on timespans in the timeline. The desired functionality for the timeline includes: Sliding to the correspondi ...

Vertical scrollbar in iframe unexpectedly appears immediately after the submit button is pressed

I have designed a contact form that is displayed in an iframe within an overlay div. I have carefully adjusted the dimensions of this div to ensure that there are no scrollbars visible when the form initially appears. However, after filling out the form an ...

JSFiddle showcasing the Bootstrap grid system

I'm having trouble implementing bootstrap's grid system on jsfiddle. Check it out on jsfiddle I've tried using the example from the bootstrap documentation: <div class="row"> <div class="col-md-1">.col-md-1</div> ...

I attempted using the regex pattern (09)[0-9]{89}, but unfortunately it does not satisfy the validation criteria I need

I attempted to use a regex expression for validation in both HTML forms and server-side validation in Laravel. However, the expression I used (i.e (0\9)[0-9]{8\9}) did not fulfill the criteria for validation: The number must start with either 0 o ...

Guide to creating scroll-based animations for a Div element

I've been brainstorming ways to rotate a div as I scroll. My goal is to recreate the effect shown in this codepen. However, I'm struggling to implement scrolling functionality. What I envision is scrolling down causing the word Data to rotate in ...

Issues with inconsistent behavior of the select option in a form

Having some trouble with my form code. When I checked the web page, there seems to be an extra element that shouldn't be there. You can view the webpage https://i.sstatic.net/pu4ef.jpg. Inspecting it in browser developer mode, I found this extra eleme ...

Is it viable to create an onClick event for the text content within a text area?

I'm working on a project that involves displaying XML data in a textarea and creating an onClick event for the content within the textarea. For example: <textarea>Hello Web, This is a simple HTML page.</textarea> My goal here is to cre ...