Attempting to align text in the middle of the homepage by utilizing display: flex while incorporating a header

I'm attempting to center the text on a webpage right in the middle using display: flex while also including a header with a logo inside it. I've successfully achieved this using the code below:

Method 1

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

The result can be seen here: https://codepen.io/pen/QWKrrNq

However, when trying to accomplish this with display: flex using the following code:

Method 2

height: 100%;    
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;

The outcome is visible here: https://codepen.io/pen/wvzjjMJ

With method 1, the text is perfectly centered, but with method 2, it's not.

The reason for this discrepancy lies in the height taken up by the header, affecting the space available for centering the text div. I wonder if achieving what was done in method 1 is possible through display flex?

I have experimented with changing the height of the text container div from 100% to 80%, 70%, etc., which initially works, but as the viewport width changes, the text becomes off-centered unlike in method 1. The only solution seems to be using media queries for different heights percentages.

Is there an easier way to accomplish this using display: flex?

Thank you.

Answer №1

The key to centering elements using flexbox lies in the code below:

height: 100%;
display: flex;
align-items: center;
flex-direction: column;
margin-top: 50px;

To perfect the centering effect, eliminate justify-content center and instead, incorporate margin top or padding top to the div

Answer №2

To effectively address this issue, I suggest utilizing absolute positioning for the header__nav element, similar to what you did in your initial example. By doing so, the header__text element will no longer be relative to the nav, allowing the nav to remain fixed at the top of the page, as desired.

Furthermore, in your second demonstration, incorporating the following positioning rule:

    &__nav
        display: flex;
        padding: 1rem;
        position: absolute;

resulted in centering the header text successfully on my end.

Answer №3

The alignment is slightly off because the element header__nav is taking up space and pushing content downward.

Consider whether you want the navigation to always appear on top, perhaps using position: absolute. The following code snippet can help center the title:

*,
*::after,
*::before {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}

html {
  font-size: 62.5%;
}

body {
  box-sizing: border-box;
  line-height: 1.7;
  color: white;
  padding: 1rem;
  font-family: "Andika New Basic", sans-serif;
}

.container {
  margin: 0 auto;
  position: relative;
}

.header {
  height: 95vh;
  background-image: linear-gradient(to right top, #7cc071c0, #168042a2), url(../img/hero.jpg);
  background-size: cover;
  background-position: top;
  background-repeat: no-repeat;
  clip-path: polygon(0 0, 100% 0, 100% 80%, 0% 100%);
}
.header__nav {
  display: flex;
  padding: 1rem;
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
}
.header__nav--logo {
  max-width: 15%;
}
.header__text {
  height: 100%;
  display: flex;
  text-align: center;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.header__text--title {
  letter-spacing: 1rem;
  text-transform: uppercase;
  font-size: 2.5rem;
}
.header__text--copy {
  letter-spacing: 0.3rem;
  margin-top: 2rem;
  font-size: 1.6rem;
}
<body>
    <section class="container">
        <header class="header">
            <div class="header__nav">
                <img class="header__nav--logo" src="https://github.com/jonasschmedtmann/advanced-css-course/blob/master/Natours/starter/img/logo-white.png">
            </div>
            <div class="header__text">
                <h1 class="header__text--title">
                    Welcome to my website
                </h1>
                <h2 class="header__text--copy">
                    Click the buttons below to enter
                </h2>
            </div>
        </header>
    </section>
</body>

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

Creating an Android button styled in blue using HTML

When using my android smartphone, a button on my website gets a blue selection color when clicked, but this does not happen when using a desktop browser. I have tried using outline:none but it doesn't work. button:active { outline: none ! ...

Tips for lining up items in a row

I am struggling to align these boxes next to each other instead of on top of each other. It seems like it should be an easy task, but I just can't seem to make it work. Check out my code here for reference. <body> <div class="horAlign"&g ...

Adjusting iframe height based on content in ReactJS

When tackling this problem in a React environment, the traditional solution falls short due to the dynamic component structure and event model: script: <script> function resizeIframe(obj) { obj.style.height = obj.contentWindow.document.body.s ...

Having difficulty altering the div color in real-time using VueJS

I'm currently in the process of building an application with Bootstrap and VueJS. My goal is to create a folder structure similar to Google Drive, where I want to make a div stand out in blue once it's selected. Below is the code snippet: ex ...

Is there an issue with CSS animation glitches in Chrome? Specifically referring to the width transition effect on a centrally

I recently encountered a strange issue with my centered div layer that transitions from a fixed width to 100% when scrolling down. The problem arises in Chrome and Edge on Windows 10, where certain elements like images shake and jitter during the transitio ...

Tips for creating animations with multiple elements that share the same classes

I am trying to create expandable boxes that can open onclick and close again by clicking on the X. The issue I'm facing is that the close jQuery function isn't working. However, my main concern is how to optimize the code so it doesn't becom ...

How to Implement Angular ngStyle with ChangeDetectionStrategy.OnPush?

Check out this StackBlitz demonstration that demonstrates how ngStyle is being used to style the h1 element in the following way: <h1 [ngStyle]="{'background-color': backgroundColor}" The component named HelloComponent employs the O ...

I'm puzzled as to why my JavaScript code only functions correctly when I place it after the HTML, despite having a window.onload event handler in place

Just beginning my journey in a CS class and seeking guidance for my lack of basic knowledge. I've noticed that this JS code only works if placed after the HTML, not within the head tag. Shouldn't window.onload handle that? Can someone clarify wha ...

When attempting to set a video as the background on the landing page, the Z-Index feature does not seem to function correctly

As a beginner in front-end development, I decided to challenge myself by creating a web portfolio from scratch. To personalize my landing page, I wanted to use my video editing reel as the background, but for some reason, it just wouldn't work. Even w ...

Retrieve an HTML element that is a select option with jQuery

I have a select input containing different options as shown below: <select id="myArea"> <option class="myClass_1" style="color:red;" value="1">Area 1</option> <option class="myClass_2" style="color:green;" value="2">Area 2& ...

Issue with triggering function within Material UI Tabs

The issue I encountered cannot be replicated, but I attempted to address it. Within a Material UI element, there is a child element that I inserted - an X icon located in the corner. The parent element is the surrounding box. There are two main problems: ...

Guide for initializing the scroll percentage update when the element reaches the top of the viewport in JavaScript

Upon entering the website, the initial UI that greets you can be seen here: https://i.sstatic.net/Z3eIl.png As you scroll down to the very beginning of section B I anticipate that section B will stick in place and the state of currentPercentage will gra ...

How can you use jQuery to select and manipulate a wildcard href ID?

There are multiple links listed below: <a href="http://www.google.com" id="link01">Google</a> <a href="http://www.yahoo.com" id="link02">Yahoo</a> <a href="http://www.cnn.com" id="link03">CNN</a> <a href="http://www. ...

Enhance the v-autocomplete dropdown with a personalized touch by adding a custom

Currently utilizing the v-autocomplete component from Vuetify, and I am interested in incorporating a custom element into its dropdown menu. You can see the specific part I want to add highlighted with a red arrow in this screenshot: This is the current s ...

Customize the Facebook like box to match the dimensions of the image

Take a look at my code in this fiddle for some context: http://jsfiddle.net/GgvLQ/ I've been tasked with creating a design where a set of Facebook links needs to always align with the bottom of an image that's situated next to them, regardless ...

What is the best way to make hyperlinks in impress.js?

Wanting to craft a visually stunning brochure for my client with the help of impress.js. I want to include a link on each slide that directs to the relevant page when clicked. Is it feasible to have a clickable link to each slide on every page as well? ...

reducing the size of the text field

Is there a way to adjust the height of the text box? So far, modifying the style sheet hasn't worked. Below is my code along with the corresponding style sheet. <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css ...

Selecting dropdown list values with Selenium in C#

I'm encountering an issue while trying to populate a dropdown list using Selenium WebDriver in C#. Below is the snippet of HTML code: <div class="chosen-container chosen-container-single chosen-container-single-nosearch" style="width: 278px;" tit ...

What is the best way to update a canvas chart when the side menu is hidden?

I am facing an issue with the layout of my webpage, which includes a left side menu and a canvas chart. The left side menu occupies the first 155 pixels of the width, leaving the rest for the canvas chart set to a width of 100%. However, when I close the ...

Steps for inserting an icon tag within a text input field

In this section, I have created a div class that contains an image tag to display the profile picture. Following that, there is a <TextInput> element styled using CSS. Outside of the <TextInput/>, there is a custom button for submitting posts. ...