How to horizontally center a div with margin using CSS

Is there a way to horizontally center a div with margins using CSS?

<div id="container">
    <div id="center_me"></div>
</div>


#container{
    position:relative;
    width:100%;
    height:400px;
}

#center_me{
    position:absolute;
    width:100%;
    margin:0 50px;
    max-width:300px;
    height:100%;
    left:50%;
    -webkit-transform:translateX(-50%);
}

I want to maintain a margin on the centered div, so setting margin:0 auto won't work. The technique I am using with "left:50%" and "translateX(-50%)" does not account for the margin. Is there a way to achieve this fluidly while keeping the same fixed margin when the window size changes? Am I missing something obvious?

http://jsfiddle.net/R3yny/

Pure CSS solutions only please. Thank you.

Answer №1

Is there a way to apply the margin to a different div that is nested inside #center_me?

<div id="container">
    <div id="center_me">
        <div id="i_have_the_margin"></div>
    </div>
</div>

Instead of adding margin directly to #center_me, you can apply it to #i_have_the_margin like this - http://jsfiddle.net/nickg1/R3yny/3/ (Tested in Opera)

Answer №2

When trying to position an element on a webpage with a responsive design, it's important to consider the impact of margins on centering. If you offset an element from the center using margins, it may no longer appear centered.

To achieve a central-ish positioning, one approach is to use percentage-based margin widths and visually adjust the placement until it appears centralized. Here's a simple example:

http://codepen.io/staypuftman/pen/oHGAF

CSS:

.hero-text-area-container {
  background: #d6ffd1;
  float: left;
  margin: 0% 30%;
  padding-top: 20em;
  position: relative;
  width: 50%;
}

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

Imagine a webpage with a width of 1000 pixels. Can you determine the precise horizontal position (from the left) of the div element with the unique id of "inner_div"?

Hello everyone, I hope you're doing well. I recently took a test and unfortunately got this question wrong. Imagine a web page with a width of 1000px. What is the exact horizontal (from the left) position of the div element with id "inner_div"? < ...

Could Flexbox CSS be used to create a responsive layout like this?

Appreciate your help in advance. I am facing a challenge with the current layout. <article> <section class="content">1</section> <aside class="ads">2</aside> <section class="comments">3</section> < ...

Mobile menu in Bootstrap failing to show up

Hello, I am creating a website using Bootstrap and I am encountering an issue with the hamburger menu not appearing when I resize the screen. Here is the code I am using: <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi ...

Styling with CSS to accentuate the currently active tabs

Struggling with writing CSS to meet the following requirements after creating a tab and calling a function on click: 1. The active tab should display a blue underline color. 2. When clicking on a tab, the blue line should appear under the active tab (sim ...

When the Model popup is activated, it is essential for elements to have an adequate color contrast

Our team is utilizing the axe dev tool for accessibility testing. We encountered an issue where elements behind a model popup (Kendo React model with position: absolute) were displaying insufficient color contrast errors. Upon changing the absolute positio ...

What steps can be taken to ensure that a dropdown menu responds instantly to the JavaScript code provided?

Upon discovering this code snippet in a different answer (on jsfiddle), I noticed that it allows for the appearance of a text box when the user selects 'other' from the dropdown menu. However, when I include '<option value='0' s ...

Basic JavaScript framework centered around the Document Object Model (DOM) with a module structure similar to jQuery. Currently facing challenges with

In order to create a simple framework with jQuery style, I have written the following code: (function(window) { window.smp=function smpSelector(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; if (!s ...

What is the process of running PHP in a .ctp file within the CakePHP framework?

I have recently started working with CakePHP and I have a question about how PHP code is executed in a file with the .ctp extension. Can you explain how PHP is processed within a .ctp file in CakePHP? Additionally, I'm also curious about executing PHP ...

Masonry style attempted for posts but did not produce desired outcome

I've been experimenting with different methods to achieve a masonry style layout for my posts. So far, using float:left seems to work almost perfectly, but occasionally there are gaps between the posts. I'm on the lookout for a solid solution to ...

What is the best way to set up user comments in a Mysql database?

Recently, I've been working hard on building a blog from scratch. However, I encountered a major issue with the comment section. The form prompts users to enter their Name and Comment, which are stored in the following database fields: `comname` VARC ...

Enhance Animation Fluidity with HTML/CSS

I am experimenting with creating a floating animation for my iceberg logo by adjusting the top margin. Below is the CSS code I have implemented: img { height: 60px; padding: 5px; -webkit-animation: logofloat 1s ease-in-out infinite alternate; -moz ...

Step-by-step guide on sorting WordPress posts by a custom field date

I've created an event sidebar section that will only show the next 3 upcoming events. I have successfully set up the custom post type and custom fields, but I am struggling to figure out how to order the posts based on the start date of the events, wh ...

encountering a Zend Framework error

Looking for help with printing data after an inner join of two tables in table format. I encountered the following error in the code below: Parse error: syntax error, unexpected end of file in /home/bina/public_html/studentzend/application/views/scri ...

Ways to eliminate the border color from bootstrap multiselect

I have been attempting to eliminate the border color surrounding options in a select box from Bootstrap Multiselect. Unfortunately, I am unable to identify the specific class responsible for adding the blue color around the option borders. This border app ...

Styling div elements within other div elements using CSS

I am currently working on creating a layout with three divs, each containing an image. The challenge is to set the height of the first div (top) to 10% of the screen size, the second (middle) to 60%, and the third (bottom) to 30%. I want these divs to main ...

Creating transparent overlay boxes with CSS grid

I'm working on a design where I need to display text information over an image. The challenge is aligning the text properly, especially when the screen size changes due to using a grid system (1140). Currently, I have a div with transparent background ...

Placing a component within a .jsx file instead of utilizing a .css file for positioning

Seeking a way to position a component within a .jsx-file, rather than a .css-file, to accommodate multiple instances of the same component performing various tasks on different parts of the page. Avoiding duplication of files with minor CSS class changes, ...

The button now has a stylish 5px border, making it slightly larger in size. However, it seems

How can I add an active class with a 5px border-bottom on a button without increasing the button size by 5px? The box-sizing property is not working for me. Is there a simple solution to achieve this? *, *:after, *::before { -webkit-box-sizing: border ...

Tips for creating visually appealing tables in ReactJS

For my school project, I need to create a table using ReactJs. I have already created the table but it needs improvement in terms of design. However, I am unsure how to modify my code to achieve the desired look. I tried looking on YouTube for tutorials, b ...

Inject JavaScript Object Information into Bootstrap Modal

After iterating through each object and assigning its data to an individual div along with a button, I encountered an issue. When testing the buttons, I noticed that only the last object's data was displayed in all of the modal windows. Any suggestion ...