Struggling to center the hidden divs both vertically and horizontally on the page when they are made visible

I'm having trouble aligning my hidden divs in the center of the page.

When I set their position to relative, the scroll increases as I move from one page to another (meaning the div is not vertically centered on the page).

Should I place all three divs in one container div?

Please help!

Thank you in advance.

<body>
    <div id ="page1" class="page" style=""visibility:visible>
        content
        <!-- also contains a button that hides this div and makes the
            next div visible -->
    </div>
    <div id="page2" class="page">
        content
        <!-- also contains two buttons for back and next div -->
    </div>
    <div id ="page3" class="page">
        content
        <!-- contains two buttons for back and submit -->
    </div>
</body>

The css code I'm using:

.page {
    position: absolute;
    visibility:hidden;
}

The javascript code I've implemented is:

<script language="JavaScript">
var currentLayer = 'page1';
function showLayer(lyr){
hideLayer(currentLayer);
document.getElementById(lyr).style.visibility = 'visible';
currentLayer = lyr;
}

function hideLayer(lyr){
document.getElementById(lyr).style.visibility = 'hidden';
}
</script>

Answer №1

If you want to center your div using the current setup, check out this DEMO http://jsfiddle.net/kevinPHPkevin/g8r7Z/

#page1 {
    position:absolute;
    top:50%;
    right:0;
    left:0;
    background:#ccc;
    width:200px;
    margin:-50px auto 0 auto;
}

Answer №2

How to use absolute positioning to center an element without it being affected by height and width.

.center-align{
 position:absolute;
 top: 0;
 left:0;
 right:0;
 bottom:0;
 margin:auto;
 width: /* adjust to any width */;
 height: /* adjust to any height */;
 /* other styles do not impact it */
}

The alignment remains centered even when the window is resized

Answer №3

If you need to center an element using absolute positioning, follow this code:

.container {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 50%;
    height: 50%;
    margin: -25% 0 0 -25%; /* adjust based on your width/height */
}

Remember to customize the width and height values according to your requirements. As mentioned in the comment: margin-top should be set to height * -0.5 and margin-left should be set to width * -0.5.

Check out a demo here.

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

CSS Duo-Toned Background

I've been searching everywhere for a solution to this issue. I have a design that I'm attempting to code using divs and CSS. The top half of the image features a gradient that transitions from left to right with different colors. My struggle lies ...

Filtering arrays using Vue.js

I have developed a sample e-commerce website to showcase various products to potential customers. The website boasts features like filters, search functionality, and sorting options to enhance the user experience. However, I've encountered an issue sp ...

Tips on eliminating horizontal scrolling in HTML and CSS

I am working on a simple web page template and encountering an issue with a horizontal scroll appearing on the page. I would like to remove it. Below is the code I am using: <html lang="FA"> <head> <meta charset="UTF-8&qu ...

Add Content to Textbox by Clicking

In my current setup, I have a variety of buttons that, when clicked, should add the text from the button to a text box. Each time a button is clicked, I want the text to be appended to whatever is already in the input field. Current Approach $('#js- ...

Using Promise.reject within an Ionic component's page

Within a component, I am invoking a service method that provides me with a Promise. Based on whether the promise is resolved or rejected, I need to perform different actions. This is how I am handling it: The code snippet responsible for calling the servi ...

Eliminate square brackets from URL containing an array of IDs using Request.js

My nodejs express application is sending requests with an array parameter, but it's including '[]' in the query string: For example: /foo?id=1&id=3&id=5 How can I remove the square brackets '[]' from the query string? va ...

Building an integrated Monaco editor using Electron and AngularJS

Struggling to integrate the Monaco editor into my Electron app. Despite following electron examples, encountering persistent errors in my application. The errors I'm facing include: "loader.js:1817 Uncaught Error: Unrecognized require call" "angula ...

Issue with ThemeManager in Material UI & React: Constructor is not valid

Currently, I am integrating Material UI into a small React application, but I suspect that the tutorial I am following is outdated and relies on an older version of Material UI. The error _materialUi2.default.Styles.ThemeManager is not a constructor keeps ...

Possible conflict between CSS and JavaScript on Magento website

Problem Description: Visit this link for more details I am facing an issue with the product upload process when using certain attributes. It appears to be related to a positioning problem. Despite trying various solutions, such as removing the position at ...

When dynamically adding input data, the serialized array may not successfully pass through Ajax

function SubmitData(){ var postData = $("#xForm").serializeArray(); $.ajax({ type: "POST", url: "mail.php", data: postData, success:function(data){ console.log(data); }, error: function(jqXHR, textStatus, errorThrown ...

Innovative react route

Currently, I am in the process of learning about dynamic react routes. In the code example I am working on, there are different buttons for each task. The goal is to render the WorkDetails component when a button is clicked. However, it seems to not be fun ...

Dealing with a 404 Error in Node.js and Express Routing

After successfully creating a Node/Express app tutorial earlier, I encountered issues when trying to replicate it for a new project on both Ubuntu and Windows. The basic routing consistently fails and results in 404 errors, which is incredibly frustrating! ...

Opening a Material UI dialog results in a change in the style of other components

Whenever I open the Dialog component from a button on the AppBar component, the margin on my navbar elements changes unexpectedly. I have checked the HTML using dev tools and there are no CSS changes on either of the components. Any suggestions on how to p ...

Error 500 - NodeJS API Updater Experiencing Technical Difficult

Time to bring in the experts because I'm stuck on this issue. I have a basic CRUD API built with Node and EJS on the front-end. The problem lies in the selectAllRecords view where I display a table of all records. Each record has an edit button tha ...

Loading an empty CSS file in Node.js

Just starting out with node.js, and I could really use some help with a small css and image issue that I'm facing. I've streamlined my html and .js for clarity. Despite trying everything, the css and image just won't load. My form and server ...

How to pass the id value between pages in web developmentactics?

I've been struggling to call the id value of one page in another for a while now. I assigned the id value "addedcart" to the form and tried to call it in my PHP code, but no cart value is being displayed. I'm not sure if I am calling the id corre ...

An effective way to eliminate or verify duplicate dates within an array in AngularJS1 is by employing the push() and indexOf() methods

I have successfully pulled EPOCH dates and converted them into strings, but my previous code did not check or remove duplicates. Does anyone have any suggestions on what I can add to accomplish this? The timestamp in this case is the EPOCH date that I re ...

Concentrate on Managing Text Input Fields in Zend Form

I designed a form using Zend Form and want the focus to be on a text area within the form when the page loads. I attempted to use JavaScript for this purpose, but it only briefly shows the focus before removing it again, preventing any typing. I considere ...

gulp-minify-css-names not altering any files during processing

For quite some time, I have been on the search for a solution that can assist me in automating the process of renaming/minifying class names in HTML, JS, CSS files simultaneously throughout my entire project using gulp. While there are many solutions avai ...

What could be causing my bootstrap carousel slider to stay stuck in place?

Hey everyone, I'm having trouble getting the carousel from Bootstrap to work properly. I copied the code without making any changes, but for some reason, the carousel is not functioning (can't move to the next slide). Does anyone have a solution ...