Centering an element within a DIV using responsive absolute positioning

How can I ensure that the blue box always stays centered within the red box when resizing the window? Currently, it's not in the correct position. View the example online: http://jsfiddle.net/NVjPF/ Thanks!

<div id="box1">
    <div id="box2"></div>
</div>

#box1{
display: block;
background:red;
background-size: 100%;
position: relative;
padding-bottom: 60%;
}

#box2{
    display:block;
    background:blue;
    position:absolute;
    height:70px;
    width:70px;
    right:50%;
    top:50%;
  }

Answer №1

It has been mentioned by others that in order to properly center the box, you must include

margin:-35px -35px 0 0;

This ensures that the box will always be centered regardless of screen size. The reason for this is because the browser aligns the upper right corner of the box to the center, giving the appearance of being centered. If you were to use left:50%; instead of right:50%;, the box would be centered based on the upper left corner. To resolve this issue, you need to calculate half of the width and height to find the true center of the box.

To prevent the box from extending beyond the red box, I have added overflow:auto; to create scrollbars when necessary. If you prefer not to show scrollbars, you can change it to overflow:hidden. Both options will work to prevent any protrusion.

http://jsfiddle.net/burn123/NVjPF/3/

Answer №2

To adjust for the variance, negative margins can be utilized. Specifically, the following can be included:

margin-right: -35px;
margin-top: -35px;

The value of 35px is derived from half of the inner element's size. Check out this live demonstration at http://jsfiddle.net/NVjPF/1/.

Answer №3

Give this a shot. Essentially, you shift the box halfway within its parent container and then reposition it to the exact center using negative margins that are half of the box's width and height.

#box2 {
display:block;
background:blue;
position:absolute;
height:70px;
width:70px;
right:50%;
top:50%;
margin:-35px -35px 0 0;
}

Answer №4

I've found this method to be very effective:

#container {transform: translate(-50%, 0%);}

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

Mobile FPS suffering due to slide-out drawer performance issues

My application features a drawer menu that functions smoothly on desktop, but experiences issues on mobile devices with noticeable lag. Within the header, I have implemented a boolean value that toggles between true and false upon clicking the hamburger i ...

Enhance the functionality of jQueryUI sortable by enabling scrolling and incorporating a delay specifically for mobile

I have an inline thumbnail gallery that can be sorted using jQueryUI and the touch punch plugin for mobile devices. Everything is functioning correctly, except on mobile devices with a large number of images. I am unable to scroll down the screen to view ...

What is the best way to align the bottom of an element with the browser buttons panel on mobile devices?

When viewing the website on a mobile device, I noticed that the floating button is hidden behind the browser buttons panel. Is there a way to adjust the positioning of the element relative to the browser's buttons panel? I attempted using env(safe-ar ...

Contrasts in characteristics of CSS images versus SVG graphics

I'm curious if there are distinctions between CSS images and SVGs on your website. When referencing CSS images, I mean images constructed with div elements in HTML and then styled using CSS (such as this: https://codepen.io/andrewrock/pen/jOEZxrY). ...

Bars that span the entire width of the browser

Check out my website: I want the header to be a full width blue color like this image: https://i.sstatic.net/NHMG1.jpg I attempted following this guide: https://css-tricks.com/full-browser-width-bars/ but it didn't work. Any ideas on how to achiev ...

Using CSS to overlay a fixed element with a specific z-index

HTML: <div class="wrap"> <div class="fixed"></div> </div> <div class="cover"></div> CSS: .cover{z-index: 10;} .wrap{position: relative; z-index: 1;} .fixed{position: fixed; display: block; z-index: 1;} Example: ...

Tips on implementing polymer.js to toggle the visibility of an element

On my HTML page, I have two different paper-card elements: <paper-card done> <paper-card> In addition, there is a button: <paper-icon-button icon="menu" on-tap="_show"></paper-icon-button> I am trying to utilize the _show fun ...

Customize the appearance of all QProgressBars using Qt stylesheets in your C++ program

Struggling to figure out how to dynamically apply a stylesheet to multiple or all widgets in Qt Creator 4.1 (Qt 5.7) using C++. For instance, if I have 3 progress bar widgets, currently I am setting the same stylesheet for each one individually with CSS: ...

Can anyone recommend a high-quality jQuery lightbox replica?

Key Features Needed: Customizable with CSS Capable of handling forms, not just images Extensively documented Please provide any recommendations and suggestions for suitable options. Thank you in advance ...

Code to select the first row in a table using CSS styling

I'm looking for a CSS selector to target the first <tr> in a <table>. After searching online, I found some selectors like tr:first-child and table *:first-child tr:first-child, table tr:first-child. Unfortunately, these do not work in my ...

Adding a semi-transparent layer to cover half of the canvas while still allowing the canvas to be visible

I'm struggling with overlaying a div on top of a canvas while keeping the canvas visible. Currently, I can only get the div to cover the canvas and hide it. If anyone has an example to share, that would be greatly appreciated. var canvas = document ...

Upon selecting the hamburger menu, the menu pops up; however, the homepage text is visible overlapping the menu

I'm in the process of developing a responsive portfolio page using ReactJS and Tailwind CSS. When the screen size is smaller than the medium breakpoint, a hamburger menu icon appears. However, when I click on the hamburger icon to view the menu items, ...

How come an absolutely positioned element does not disregard its sibling's position and appears after it?

<div> is styled flexibly, while <section> is inserted within it and formatted statically. However, <section> shows up underneath the lower right corner of the image, rather than at the upper left corner of its flexible parent. I am strugg ...

Overrides of variables are not always complete

After setting up my project with npm install to utilize sass overrides, I encountered an issue. Despite adjusting the $theme-colors, only part of the page reflects the change. https://i.sstatic.net/xjrsx.png I attempted the following: $theme-colors: ("p ...

What are the steps to create a DIV table after submitting a form?

I'm having trouble creating a header row for a DIV table using JavaScript (without jQuery). Instead of getting the expected output, I'm getting a row with the array items as headings separated by commas. https://i.sstatic.net/8O5QR.png var ma ...

What is the method for subtracting pixels from a percentage value?

Is there a way to accomplish a similar effect to this: height: calc(100% - 50px); height: -webkit-calc(100% - 50px); height: -moz-calc(100% - 50px); In browsers that do not support these properties? I have a responsive div with two children. The height ...

Activate the timepicker in Bootstrap when the user clicks on the input field

Struggling to implement a timepicker feature? Look no further than this resource. After adding the necessary js and css to your project, you may encounter issues with the popup not appearing when clicked. The code provided offers a TextBox control with s ...

Tips for adjusting the animation position in Off-Canvas Menu Effects

I am currently utilizing the wave menu effect from OffCanvasMenuEffects. You can view this menu in action below: ... // CSS code snippets here <link rel="stylesheet" type="text/css" href="https://tympanus.net/Development/OffCanvasMenuEffects/fonts/f ...

Fluid layout causing elements in body to be hidden by fixed header

I'm currently tackling a fluid layout challenge, utilizing percentages instead of pixels to achieve it. I've managed to create a fixed heading (#heading) at the top of the page, but now I'm struggling with ensuring that all other elements on ...

I am unable to switch my carousel to full-screen mode

I'm struggling to make the carousel fullscreen even though I've set the width to 100%. Bootstrap was used in this project. Any help would be appreciated. Thank you! <html> <head> <link href="homepage.cs ...