How can you center everything when working with child divs of varying dimensions?

I managed to get the divs to stack correctly, but I'm having trouble centering the children. The canvas and another div that serves as my input layer are the elements I am working with. The input layer is positioned on top of the canvas, covering the full screen. However, I want the canvas to be centered while keeping the input layer also centered (even though it covers the entire screen). It's important to note that I don't have fixed heights and widths because this site is responsive. I am open to solutions using pure JavaScript, jQuery, CSS3, or HTML5 as long as the end result is a centered layout.

tl;dr: div container -> (div input && canvas) parent -> (child && child) center the canvas of unknown height and width on the page

EDIT: I need the blue-ish box (canvas) to be perfectly centered on the page. http://jsfiddle.net/t2fL9/4/

Is there a code block available for me to share a JSFiddle link?

Answer №1

Here is an example of how you can update your JavaScript code:

var $container = $('#container'),
    $image = $('#image'), 
    image_width = $image.width(),
    image_height = $image.height(),
    $window = $(window);

$window.resize(function(){
    $container.css({
        width: $window.innerWidth(),
        height: $window.innerHeight()
    });

    $image.css({
        marginLeft: -image_width/2,
        marginTop: -image_height/2
    })    
}).trigger('resize');

Check out the demo

Answer №2

Here is a great solution for you, using canvas as an example.

CSS

#canvas{
position: absolute;
top:50%;
left:50%;
}

Javascript:

var canvas = document.getElementById('canvas'),
canWidth = canvas.width,
canHeight = canvas.height;

canvas.style.marginLeft = canWidth/2*-1;+"px"
canvas.style.marginTop = canHeight/2*-1+"px";

Check out this fiddle example http://jsfiddle.net/t2fL9/7/

Answer №3

If you're okay with only supporting IE9 and above, you can utilize CSS3 transform to achieve vertical alignment like so:

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

Hats off to the creator of this clever trick, which can be found at:

Check out the updated fiddle link here: http://jsfiddle.net/t2fL9/5/

For a resizing demo fiddle, click on this link: http://jsfiddle.net/t2fL9/11/

It's worth noting that achieving centering with this method requires significantly less javascript compared to other approaches.

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

What is the method for adding npm dependencies that are not included in the package.json file during installation?

I am facing an issue with running npm install. I need to install all the dependencies used in my project. In my project files, there are various instances like const mongo=require('mongoose') and const morgan=require('morgan'), even tho ...

Submenu not appearing in context menu

Check out this demo I created with a canvas menu. When you click on the canvas, a menu appears. Hover over the "Aggregate" option to reveal a second submenu on the right. The issue arises when you mouse out of "Aggregate" and then hover back in – the po ...

Guide to positioning a div at the bottom of a Drawer while maintaining the same width as the Drawer in React Material UI

Creating a Drawer on the right-hand side using <Drawer/>, I am trying to make a <div> stick to the bottom of the <Drawer />. The width of this <div> should match the width of the <Drawer />. Desired Outcome: https://i.sstati ...

The pause option in urql's useQuery function offers a temporary halt to the request and does not freeze it completely

I'm attempting to ensure that the urql useQuery function is only executed once in my code. Unfortunately, it seems to be getting called on every re-render. According to the documentation at , this query should start off paused when rendered and shoul ...

Tips for utilizing an adaptive design with Angular

I am working on designing a page that allows for scrolling if needed. On each section of the page, I will be incorporating specific components with unique colors to enhance the layout. However, my current HTML code is not producing the desired result as sh ...

The issue persists with inserting dynamic input fields into two separate MySQL tables alongside non-dynamic input fields

I am facing an issue with inserting data into two tables in the database Table 1 - Orders - id -Primary Key - name - date Table 2 - Products - product_id - Primary Key - product - id - Foreign Key There are three input fields, Name, Date, and Pr ...

Is it true that core JavaScript is not compatible with AngularJS projects?

While this may seem like a simple question to some, I have been struggling to find the answer for quite some time now. Why is it that native javascript methods like onclick do not work in my Angular 2 project? Below is a sample code snippet for reference: ...

The server sends a response with a MIME type that is not for JavaScript, it is empty

I am trying to integrate an angular application with cordova. Upon running "cordova run android" and inspecting it in Chrome, the console displays the following message: "Failed to load module script: The server responded with a non-JavaScript MIME t ...

Managing multiple checkbox selections in React.js

Hello everyone, I'm currently working on trying to assign a function to my "select all" checkbox button to toggle the state when the button is clicked. However, I seem to be encountering an issue. Can anyone lend a hand? Here is my current state: ...

Issue with Dropdown alignment in Bootstrap Navigation Menu

I'm currently utilizing Bootstrap to design a Navbar. However, I'm encountering an issue where clicking on the dropdown menu causes the items in the dropdown to extend outside of the window instead of adjusting the window size accordingly. To try ...

I am interested in utilizing props to send a variable to the view

Looking for assistance with passing the variable tmp_sell to my view. Here is the code: <p @tmp_sell="getTmpSell" >?</p> <input ref="q_subtotal" placeholder="Subtotal" @tmp_sell="getTmpSell" i ...

Solving the issue of image paths within external SCSS files in Nuxt.js

Trying to organize my component scss files separately from their Vue components has been a bit challenging. I also have a GLOBAL scss file that is not scoped, but no matter which approach I take, I can't seem to get the image paths in /assets or /stat ...

What is the best way to display a component based on the route using GatsbyJS?

Currently working with GatsbyJS and attempting to dynamically render different header components based on the URL route. For instance: mydomain.com/ should display HeaderLanding mydomain.com/blog should display HeaderMain Seeking guidance on how to imp ...

Having trouble with processing the binding? Use ko.mapping.fromJS to push JSON data into an ObservableArray

Hey everyone, I'm struggling with my code and could really use some help. I'm new to knockout and encountering an issue. Initially, I receive JSON data from the database and it works fine. However, when I click 'Add some', I'm tryi ...

Modify the properties of a specific event on a calendar in Jquery FullCalendar

I'm developing a scheduling application using jQuery FullCalendar. I want to make events editable=false for those that were not created by the logged in user, and editable=true for events created by the logged in user. Can anyone suggest how to achiev ...

Conceal elements with a single click of a button

How can I use jQuery to hide all li elements with an aria-label containing the word COMPANY when the Search from documents button is clicked? Here is the HTML code: <ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content" id="ui-id-1" t ...

Tips for dynamically loading a Jquery plugin/script when the page changes on Vue router

After searching for solutions on this platform, I have not found any that work for my specific issue. If you want to see a working example, you can check out this demo. My project is quite straightforward - it's a one-page application with Vue handl ...

Struggling with IE7 compatibility issues regarding tables inside a div? Seeking a reliable resource to gain insights and strategies for effectively resolving IE7 problems

I am currently in the process of revamping this website: but I am facing a challenge with repeating a gradient within a div (cnews). The problem arises when the gradient is repeated on IE7, as it distorts the color. It appears as though the blue in the im ...

Is there a way to remove an element from one table and add it to another table upon clicking the submit button using JavaScript?

Seeking assistance as a newcomer in the world of JavaScript. A wise quote goes here An array filled with fruits such as mango, apple, orange, and kiwi is declared as "fruits". Another thought-provoking quote follows... The task at hand involves man ...

Effortlessly altering panel attributes with jQuery in an asp.net web form

I am facing an issue with a web form that contains a panel with form elements inside it. There are also two radio buttons, and based on the selected radio button, I need to change the DefaultButton property of control panel1 to another button like "btnASWe ...