Using CSS, center a div element both vertically and horizontally, and position the footer at the bottom of the page

I am encountering some unexpected behavior for a task that I thought would be simple. I have two main objectives in mind. Firstly, I want the footer to be displayed at the bottom of the page as an actual footer. Secondly, I need the div with the ".center-div" class to be positioned at the center both vertically and horizontally on the page.

Despite trying CSS solutions found online and hoping for a breakthrough eventually, I have not been able to achieve the desired outcome. I will continue to search for solutions on Google to resolve this issue, as I am puzzled by what might be causing the problem with my code.

Below are the key sections of my HTML code. I am including the CSS CDNs I am utilizing, just to rule out any potential issues stemming from them. Also, please note that this is for a flask application:



   #page-container {
      position: relative;
      min-height: 100vh;
    }

    .center_div {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -50px;
      margin-left: -50px;
      width: 800px;
    }

    #footer {
      position: absolute;
      bottom: 0;
      width: 100%;
    }

The code snippet above provides a glimpse into the structure of my project, complete with the CSS and CDNs used for styling. The main content of the page is contained within the "center_div" div and the footer is at the bottom of the page.

If you wish to view the actual result of this setup, you can click on this screenshot link: https://i.sstatic.net/h7gHw.png

Moreover, you can access a demonstration of my complete HTML and CSS files on this JSFiddle demo link: http://jsfiddle.net/vuz6Lp1d/1/

It's worth noting that the screenshot outcome does not entirely match the rendition in the JSFiddle version. While the footer shows at the top of the page in the screenshot, the "centered" div is somewhat off-center towards the right, lacking the necessary padding on the right side.

Edit 1

The suggested solutions did not yield the desired outcome, prompting me to simplify the approach. Upon closer inspection, I realized that the original code I used was likely incorrect. Despite investing time in troubleshooting and copying solutions from Stack Overflow, the situation did not improve.

It's intriguing how margin: 0 auto; centers the div horizontally but not vertically. Surprisingly, margin: auto 0; does not work at all, causing the div to remain in the top left corner. Here's a screenshot showing the inspect element process with margin: auto 0;: https://i.sstatic.net/IgmKY.png

Consequently, I have settled for using margin: 0 auto; which only vertically centers the <div> element. As a result, the footer now sits at the bottom of the page as expected.

The revised CSS now simply looks like this:

.center-div { 
width:800px;
margin: 0 auto;
}

Answer №1

To perfectly center your content in the .center_div, you can try the following CSS:

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

Alternatively, you can achieve centering using flex properties. Here's an example:

display: flex;
justify-content: center;
align-items: center;

For universal browser compatibility, consider using margins as another approach to centering your div.

Hopefully, these suggestions will assist you in achieving the desired centering effect.

Answer №2

Success is imminent!

body {
  padding-bottom: 40px; /*height of the footer*/
}

#page-container {
  position: relative;
  min-height: 100vh;
}

.center_div {
  position: relative;
  top: 50%;
  left: 25%;
  right: 25%;
  margin-top: -50px;
  margin-left: -50px;
  width: 50%;
  padding-bottom: 40px;
}

#footer {
  position: fixed;
  bottom: 0;
  left: 0;
  height: 40px;
  width: 100%;
}
<!DOCTYPE html>
<html>

  <head>
    <title>Cutting-Edge Experiment Welcome Page</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="{{ url_for('static', filename='jspsych.css') }}" rel="stylesheet" type="text/css">
    <link href="{{url_for('static', filename='style.css') }}" rel="stylesheet" type="text/css">
    <!--  Bootstrap  css and other basic formatting -->
    <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">
    <!-- Material Design Bootstrap -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.8.9/css/mdb.min.css" rel="stylesheet">
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

  </head>

  <body>
    <div id="page-container">
      <div class="center_div">
        <h1>Innovative Cognitive Functions and Risk Assessment Task Prototype</h1>
        <p>Kindly input the number of trials you desire (from 1-100) in the designated field and hit submit</p>
        <form id="Trial_Form" action="/experiment_app" , method="post">
          <input type="number" name="trials" min="1" max="100">
          <input type="submit">
        </form>
        <p>Once submitted, the experimental application will commence, showcasing each trial interactively with the JsPsych framework.</p>
      </div>



      <footer id="footer" class="page-footer unique-color">
        <img src="{{ url_for('static', filename='images/cognew_logo.png')}}">
      </footer>
    </div>
  </body>
  <script>
    $("#Trial_Form").submit(function(event) {
      alert("CUSTOM ALERT MESSAGE");
    });

  </script>

</html>

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

searching backwards using regular expressions

I have successfully extracted <%? imagepath;%> using the following regex from a string. <%(\?|.|\s)*%> <img src="http://abc/xyz/<%? imagepath;%>.gif"> <img not_src="http://abc/xyz/<%? imagepath;%>.gif"> <i ...

Maintain the text layout when copying and pasting from the Angular Application

After noticing that copying and pasting text from an Angular Application to a text editor like Microsoft Word results in losing the original format, I decided to investigate further. An example I used was the angular material website: https://material.ang ...

How can you transform attribute and value pairs from a DOM element into a JavaScript object?

Is there a quick method to transform a DOM element along with its attributes and values into a JavaScript object? For example, converting this snippet from the HTML page: <div id="snack" type="apple" color="red" size="large" quantity=3></div> ...

Using Angular JS to connect Promises while preserving data

There have been discussions about chaining promises, but this scenario presents a unique challenge. I am currently working on making multiple http get requests in my code. The initial call returns an array, and for each object in this array, another http c ...

What is the purpose behind certain developers specifying font size twice using different units?

When creating website themes, I often come across developers defining properties twice with different units. For example: body, button, input, select, textarea { color: #404040; font-family: sans-serif; font-size: 16px; font-size: 1rem; ...

Constructing a Primeng MessageService causes a blank webpage to appear

After downloading the QuickStart CLI of PrimeNG for Angular, I added a second component for a chart that was already included in the UI components. Everything seemed to be set up correctly, but when I saved, I ended up with a completely blank page for the ...

How to Navigate Downward with the Arrow Key in Python Selenium on a Mac Operating System

I am attempting to access a Drop-Down Menu on a website and choose a specific value. I am not sure how to click on an item within a Drop-Down Menu, so my idea was to instruct the WebDriver to use the Arrow-Down Key multiple times before pressing the ENTER/ ...

Error in ReactJs production code: ReferenceError - the process is undefined

Having some trouble with my ReactJs production code not recognizing environment variables. The error message reads: Uncaught ReferenceError: process is not defined <anonymous> webpack://testProject/./src/agent.js?:9 js http://localhost:8080/s ...

Every time I try to create a new React app, I consistently run into the same error

I keep encountering this error every time I try to create a React app using create-react-app. ...

Explore an array of elements to find the correct objectId stored in mongodb

element, I am faced with a challenge of searching through an array of objects to find a key that contains nested object id for populating purposes. Exploring My Object { service: 'user', isModerator: true, isAdmin: true, carts: [ ...

Menu Design Inspired by Amazon Using jQuery

Can someone please assist me in locating a jQuery Amazon-style menu example? I would like to implement something similar and am hoping to avoid having to write it from scratch. Thank you! ...

Is there a way for me to activate onMouseEnter on elements that are positioned behind other elements

I'm attempting to activate the mouseEnter event when the mouse is over multiple elements simultaneously. The goal is for both mouseEnter events to be triggered when the mouse reaches the center, and ideally for both elements to change to a yellow col ...

A guide on executing multiple Post Requests in Node.js

Currently, I am facing some issues with my code while attempting to make multiple post requests based on certain conditions. The goal is to retrieve data from an online database (Firebase), save it locally, and then delete the online data. Here's wha ...

Tips for changing the color of shapes when hovering over an image state

I have arranged three images in a column and applied column-count: 3; along with setting border-width for those images. Now I am curious about how to create the hover state for these images. Here is the HTML code snippet: <div class="wrap"> < ...

Struggles with organizing tables in asp.net

My apologies for my lack of knowledge in this area, but I am struggling to make my table look correct on my webform. I begin by creating a table: <table> </table> And I want to add a border. The traditional way is to use the 'border&apo ...

New and improved Bootstrap 5 menu bar

I am seeking to customize my navigation bar by adding a black background that spans its entire length. I do not want to rearrange the links or logo; just apply a background color. Another issue arises during SASS compilation: I am trying to change the col ...

Adjust the text color when hovering with the style tag

When it comes to customizing the color of a link on hover, CSS makes it simple with code like this: .myId:hover{ color:green; } But what if you're using inline styles? Is there a way to achieve the same effect without just plain HTML and CSS? & ...

"Interactive" - Utilizing javascript and html5 to create engaging game animations

Imagine I have a base class that looks like this: function Tile(obj) { //lots of default variables such as colors and opacity here } Tile.prototype.Draw = function () { ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," ...

How can Angular incorporate JSON array values into the current scope?

I am currently working on pushing JSON data into the scope to add to a list without reloading the page. I am using the Ionic framework and infinite scroll feature. Can someone please point out what I am doing wrong and help me figure out how to append new ...

What causes my paragraph textContent to vanish after briefly displaying its value?

As a beginner in JavaScript and HTML, I am taking on the challenge of learning these languages from scratch independently. I have encountered an issue with my code where the word "Hi!" briefly flashes below the "Click Me!" button before disappearing compl ...