I'm wondering why using display flex with justify-content center and align-items center is not properly centering the elements both horizontally and vertically. Can anyone explain this?

As I delve into the world of JavaScript, I find myself coding simple JS, HTML, and CSS snippets to enhance my learning experience. These exercises help me grasp the concepts well enough to create various JS web elements and projects. My goal is to eventually apply this knowledge to larger projects down the line.

In my current practice, I am utilizing the following CSS properties:

display: flex;
align-items: center;
/* AND */
justify-content: center;

I have applied these properties to the "body" in my CSS file, expecting it to automatically center elements both vertically and horizontally on the page. Despite not having conflicting CSS rules, I noticed that the elements were centered horizontally but not vertically.

Upon inspecting the element and manipulating the element.style within the <html lang="en"> tag by adding height: 100%;, I was able to achieve vertical centering. This workaround feels unnecessary as I believe elements should center without explicitly setting a height of 100% for the <html lang="en"> element.

This discrepancy has left me puzzled. I typically code using Visual Studio Code and preview the HTML file with the LiveServer extension. My recent focus on mastering Flexbox aligns with my newfound dedication to pursuing a career in coding post-online schooling.

Below is the snippet of my code which may shed some light on the situation:

body {
  background-color: #dbdbdb;
  display: flex;
  align-items: center;
  justify-content: center;
}

.arrows {
  height: 70px;
}


/* .left-arrow {
  display: flex;
  align-items: center;
  justify-content: center; */
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 50px;
}

.top {
  display: flex;
  align-items: center;
  gap: 50px;
}
<div class="container">
  <div class="top">
    <img src="images/left-arrow.svg" class="arrows arrow-left" alt="Left Arrow">
    <div class="frame">
      <div class="slider"></div>
    </div>
    <img src="images/right-arrow.svg" class="arrows arrow-right" alt="Right Arrow">
  </div>
  <div class="bottom"></div>
</div>

<script src="slider.js"></script>

The slider.js file currently contains no code as I haven't progressed that far. Despite experimenting with different heights (100% vs. 100vh) across multiple CSS classes, the issue persists. I have even removed certain HTML and CSS elements in an attempt to troubleshoot, yet the mystery remains unsolved.

Answer №1

Ah, the never-ending struggle of centering content in the body...

The issue lies in the fact that the body's height is not automatically set to 100% of the viewport height. If your content doesn't fill this height, you'll need to manually adjust it like so:

body {
   height: 100vh;
}

The "vh" unit represents "Viewport Height," meaning setting the body's height to 100vh ensures it fills the entire viewport. Interestingly, simply setting the body's height to 100% won't suffice! This can be a bit confusing, but let me explain further. When you use:

body {
   height: 100%;
}

This sets the body's height to be 100% of its PARENT ELEMENT, which is the html tag. Note that if you don't set a height for the html tag, it will be determined by its child elements.

I hope this explanation clears things up and helps you solve your dilemma. Feel free to reach out if you encounter any further issues!

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

The flipping CSS code will not be compatible with IE 11

I'm experimenting with creating a flip animation that reveals link text when images are flipped. Everything works fine in most browsers, except for IE11. Apparently there's an issue with transform-style: preserve-3d; in IE10, but being new to CS ...

The crash during compilation is triggered by the presence of react-table/react-table.css in the code

My code and tests are functioning properly, but I am facing a challenge with my react-table file. The react-table.js API specifies that in order to use their CSS file, I need to include import "react-table/react-table.css"; in my react-table.js file. Howev ...

Guide on inserting HTML text box form input into Express route parameter

I'm currently working on implementing a feature that allows users to search through my mongo database using an endpoint structured like this: app.get('/search/:input', function(req, res){ console.log(`get request to: /members/${req.params ...

How to place a button in the bottom center of a panel using asp.net

After learning about centering a button at the bottom-center inside a div, it became clear that it's similar to centering a button within a panel. I managed to achieve this by adding the following CSS to the button: position:absolute; margin-left ...

Issues with jQuery functionality occurring when trying to display or hide div contents on dynamically loaded AJAX content

I have encountered an issue while working on a project that involves showing or hiding a div based on the selection of a drop down value. The show/hide functionality works perfectly when implemented on the same page, but it fails when I try to do the same ...

Displaying article title above container with backdrop picture

Currently, I am working on a specific layout design using Bootstrap 5 where I am trying to render a tag outside its original container so that it takes up the full width of the page. My attempts with absolute positioning on the img tag have proven to be ch ...

Toggle the visibility of table rows based on a specific class using a checkbox

I am currently working on a code that displays the results of a query in a table format. I would like to have the ability to click on certain elements to show or hide them. I know this can be achieved using toggle and CSS, but I keep encountering obstacles ...

Analyzing an HTML document

My current challenge involves extracting the username from an HTML Page based on who is accessing it. The username is displayed on the page, but its location may vary depending on the user. I'm curious to hear how others would approach this issue. My ...

Utilize SVG background with transparent text for a clear view of surrounding content

I'm looking for a way to overlay a video with a semi-transparent black div that includes text and a button, while still allowing users to see the video playing behind it. I previously achieved this using a PNG image but now need to apply the effect to ...

Having trouble seeing the output on the webpage after entering the information

I can't seem to figure out why the result is not displaying on the HTML page, so for now I have it set up as an alert. <h1>Factorial Problem</h1> <form name="frm1"> Enter any number :<input type="text" name="fact1"& ...

My jQuery code seems to be in order, so why isn't it working as expected?

I've been attempting to create basic jQuery play/pause buttons for an HTML5 video, but when I click on them, nothing seems to happen. If you have any code that could help with the play/pause functionality, I would greatly appreciate it. Here is the c ...

Adjust the color of error messages in shiny from red

Currently, I am in the process of developing a Shiny app that includes numerous plots. Whenever I adjust any input parameters, there is a brief moment where the plots do not display before they are rendered, accompanied by a prominently displayed red error ...

JavaScript: create a button that dynamically changes size and color when scrolling

I have a pulsing button (#scrollarrow) at the bottom of my website that disappears as I start scrolling. The jQuery code responsible for this effect is as follows: $(document).ready(function(){ $(window).scroll(function(){ if ($(thi ...

CSS documents are being displayed as type text/plain

My goal is to host my static blog (built with Jekyll) on my Ubuntu server, but I'm encountering a problem where the CSS isn't being applied and I keep seeing this error: "Resource interpreted as Stylesheet but transferred with MIME type text/pla ...

Bulma: Tips for creating equally sized buttons?

I am working with Bulma CSS and trying to ensure that all my buttons are the same size. Currently, each button appears to have a different size based on the text content. I have looked into using the "is-fullwidth" option, but it makes the buttons too la ...

Having Multiple Login Forms on a Single Page

I have encountered an issue with my login form code. It works perfectly as a single form, but I need to have 20 of these forms on one page. Despite my efforts to duplicate the code for each new form and adjusting the IDs, I am unable to make more than one ...

Can CSS calc() achieve modulus behavior?

Is it possible to dynamically adjust the height of an element based on screen size using calc(), while still maintaining alignment with a specified baseline grid? The height should always be a multiple of the defined variable $baseline. I've noticed ...

Is Flash now irrelevant? What makes HTML5 or CSS3 so powerful?

While I may not consider myself a dedicated Flash Activist, it's hard to ignore the fact that despite its flaws, there are some important uses for it on certain websites. However, with all the buzz around HTML5 and CSS3 being the future of the web, ev ...

PHP Newsletter Creator

Recently, I created a unique php newsletter script in CakePHP that allows users to utilize an in-place editor to generate HTML content for newsletters. While the functionality works well, I have encountered some challenges with a new newsletter design that ...

Parsing string to JSON object and extracting specific information

In my code, I have a variable named "response" that contains the following string: {"test": { "id": 179512, "name": "Test", "IconId": 606, "revisionDate": 139844341200, "Level": 20 }} My goal is to extract the value of the id key and store ...