The CSS property "margin: 0 auto" is failing to align content in the center

It's so frustrating... can someone please explain why the center column won't align between the left and right columns? I've been trying to use margin: 0 auto; on the center column but it's not working.

    $(document).ready(function(){
        $("#hide-show").click(function(){
            $("#panel").slideToggle();
        });
    });
        .main-wrapper{
            margin: 0 auto;
            width: 70%;
        }
        
        #panel{
            width: 100%;
            background-color: aqua;
            display: none;
            position: relative;
            float: left;
        }
        .wrapper{
            width: 100%;
        }
        .images{
            width: 100%;
        }
        #img-1{
            background: url("http://lorempixel.com/output/people-q-c-640-480-1.jpg") no-repeat center;
            background-size:contain;
            height: 300px;
            width: 100%;
        }
        .col {
            width: 32%;
            float: left;
            overflow: hidden;
            background: red;
            border: 2px solid black;
        }

        .col:last-child{
            float: right;
        }

        #testing{
            background: yellow;
            margin: 0 auto;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><br />
<div class="main-wrapper"><br />
    <button id="hide-show" name="Click me">Click me</button><br />
    <div id="panel"><br />
        <div class="wrapper"><br />
            <div class="col"><br />
                <p>Hello world! 2</p><br />
                <div id="img-1" class="images"></div><br />
            </div><br />
            <div class="col" id="testing"><br />
                <p>Hello world! 3</p><br />
            </div><br />
            <div class="col"><br />
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit veniam quisquam, rem illum dicta cumque, voluptate fugiat impedit<br />
                    beatae rerum ratione, voluptates nisi voluptate fugiat consectetur adipisicing elit. Suscipit veniam quisquam, rem illum dicta cumque,<br />
                    voluptate fugiat impedit beatae rerum ratione, voluptates nisi voluptate fugiat consectetur adipisicing elit. Suscipit veniam quisquam,<br />
                    rem illum dicta cumque, voluptate fugiat impedit beatae rerum ratione. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit veniam quisquam, rem illum dicta cumque, voluptate fugiat impedit<br />
                    beatae rerum ratione, voluptates nisi voluptate fugiat consectetur adi</p><br />
            </div><br />
        </div><br />
    </div>

    <p>Hello world! 4</p>
    </div>

If you have a moment, here is the JSFiddle link: JSFiddle

Thanks in advance!

Answer №1

elements that float can sometimes cause layout issues

especially in a 3 column display, but it's an easy problem to solve

here is a general solution:

html:

<div class='leftColumn col'> ... </div>
<div class='rightColumn col'> ... </div>
<div class='centerColumn col'> ... </div>
<div class='clearFloats'></div>

css

.col { width:32%; }
.leftColumn { float:left; }
.rightColumn { float:right; }
.centerColumn { margin:0 auto; }
.clearFloats { clear:both; font-size:0; line-height: 0; height:0;}

To prevent any strange layout issues, it's important to include the "clearFloats" div - although it may not be necessary in this particular case.

If you want to see how changing your markup and css according to the above guidelines works, check out this example link.

Answer №2

Setting the margin to 0 auto won't be effective in this case due to the presence of <code>float: left;
.

To address this issue, you can increase the width of the column to 33.33% and include box-sizing: border-box;

.col {
  width: 33.33%;
  float: left;
  overflow: hidden;
  background: red;
  border: 2px solid black;
  box-sizing: border-box;
}

Answer №3

I updated the CSS from float:left to display:inline-block;

    $(document).ready(function() {
      $("#hide-show").click(function() {
        $("#panel").slideToggle();
      });
    });
        .main-wrapper {
          margin: 0 auto;
          width: 70%;
        }
        #panel {
          width: 100%;
          background-color: aqua;
          display: none;
          position: relative;
          display: inline-block; /* Updated from float: left */
        }
        .wrapper {
          width: 100%;
          height: 800px;
        }
        .images {
          width: 100%;
        }
        #img-1 {
          background: url("http://lorempixel.com/output/people-q-c-640-480-1.jpg") no-repeat center;
          background-size: contain;
          height: 300px;
          width: 100%;
        }
        .col {
          width: 32%;
          height: 100%;
          display: inline-block;
          overflow: hidden;
          background: red;
          border: 2px solid black;
        }
        .col:last-child {
          float: right;
        }
        #testing {
          background: yellow;
          margin-left: auto;
          margin-right: auto;
        }
<div class="main-wrapper">
  <button id="hide-show" name="Click me">Click me</button>
  <div id="panel">
    <div class="wrapper">
      <div class="col">
        <p>Hello world! 2</p>
        <div id="img-1" class="images"></div>
      </div>
      <div class="col" id="testing">
        <p>Hello world! 3</p>
      </div>
      <div class="col">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit veniam quisquam, rem illum dicta cumque, voluptate fugiat impedit beatae rerum ratione [...]
    </div>
  </div>

  <p>Hello world! 4</p>
</div>

Answer №4

It seems that using margin: auto; on floating elements is not possible. To resolve this issue, I followed JaromandaX's suggestion in the comments and added float: none; to the CSS rule of the middle column. Appreciate the assistance everyone!

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

Tracing rays within 'subscenes' in three.js

Hey there, I've been experimenting with webgl_interactive_cubes.html in the three.js examples and I have a question that might seem straightforward: Can we check for ray intersection with the children of an object? For instance, if I run code like t ...

Make sure to load the <img> html tag before implementing js masonry for optimal

I am facing an issue with jQuery Masonry as it arranges my 'bricks' immediately without waiting for images to load in. Additionally, I need the images to be responsive so I cannot define their height and width like this: <img src="asas" heigh ...

Tips for creating space between words within a <p> element and lining them up with text boxes in the following <div>

Here is the code I wrote for the form: <div class="container-fluid" id="unlabelled"> <p class="bg-primary">Items<span>Quantity</span><span>In Kit</span></p> <form> < ...

The anchor is ineffective (directs to the # but stays in place)

Every attempt I've made to find a solution online has failed. When I hover over the link, it directs me to the correct URL, but the page doesn't move. I'm using an up-to-date version of Chrome. Below is the code snippet: Edit: It seems tha ...

Tips for formatting dt and dd elements side by side on one line

How can I use CSS to style the following content in two columns: <dl> <dt>Mercury</dt> <dd>Mercury (0.4 AU from the Sun) is the closest planet to the Sun and the smallest planet.</dd> <dt>Venus</dt> ...

Unlimited highway CSS3 motion

I have come across a stunning 2D Highway background image that I plan to use for my mobile racing game project which involves JS and CSS3. The image can be found at this link. My goal is to create an animation of the road in order to give players the illu ...

Connecting sound components in HTML with AngularJS

I'm having difficulty figuring out how to synchronize a function with the updates on a webpage. I currently have a checkbox that triggers a function when checked. Here is the HTML code: <input type="checkbox" value="data.id" id="status" ng-model ...

How can I utilize Material-UI's Grid component to make a single cell occupy the entire remaining horizontal space?

I am currently utilizing the Grid component from material-ui in my React 16.13.0 application. My objective is to create a row with three items. The first two items are supposed to occupy only the required space without specifying pixel values. I want the t ...

Ways to increase the count in Vue Class Bindings?

Trying to utilize Vue class bindings, but uncertain about the syntax for bindings. I aim to append a numeric value to the class attribute, for instance class = "allstar50", then employ class bindings with the v-for directive to display a list of text items ...

Distinguishing $(document).width() and $("html").width() in jQuery on Internet Explorer 11

There seems to be an issue with IE11... APPROXIMATED (I presume...) console.log($(document).width()); // 808px; EXACT VALUE console.log($("html")[0].getBoundingClientRect().width); // 807.30993px; ROUNDED DOWN (or to the nearest whole number) console ...

How do I position a div right below a button using CSS and Jquery?

I have a button that, when hovered over, reveals a hidden div element. Is there a way to position this div directly beneath the button once it is revealed? <script type="text/javascript> $(document).ready(function(){ $(".plans").hover(function() ...

Is there a way to specifically load a CSS file in Meteor for only one individual page?

Is there a way to load three specific css files only on certain pages or templates in Meteor? I attempted appending the css files to the head area upon template creation, but they ended up staying loaded even when navigating away from the page. Any sugge ...

In Python, perform an action when a video or audio file reaches its conclusion

Looking to create a python script utilizing Selenium that will automatically click a button upon completion of an embedded YouTube video. If detecting the end of the video isn't possible, I'd settle for clicking the button after 3-5 seconds of s ...

javascript display hide choose among

I am attempting to display another set of options when the user selects a specific item. For example, if the user selects "Products," then a new selection box should appear with different product types. See my code below: <html> <head> <m ...

Center user input within a div element

I am trying to achieve proper alignment of input elements within a div. When the div is clicked, the input should be displayed; otherwise, a span should be shown instead. Here is my code: <!doctype html> <html lang="en"> <head&g ...

Even after utilizing box sizing, additional margins are still contributing to the overall width calculation

Having an issue where the margin of my elements is affecting their total width, even with the box-sizing: border-box property in place. There are 2 elements - a sidebar and main content div - that stack neatly until margins are added and the sidebar moves ...

Building a local storage feature using HTML5 WebControl in a Winform application

Welcome, fellow software developers! I am currently working on a WinForm application that utilizes the WebBrowser control to host an HTML5 web app. This web app relies on two key HTML5 features: 1. Application Cache 2. Local Storage While the Application ...

Is it possible to hide a div using Media Queries until the screen size becomes small enough?

Whenever the screen size shrinks, my navbar sections start getting closer together until they eventually disappear. I've implemented a button for a dropdown menu to replace the navbar links, but I can't seem to make it visible only on screens wit ...

vertical-align applied to table cells creating a floating effect

I have discovered that by adjusting the display property of the containing block to table and enclosing descendant block boxes in boxes with display property set to table-cell and vertical-align property set to top, it produces the same effect as if the fl ...

The Angular checked functionality is not working as expected due to the presence of ngModel

Just getting started with Angular here. I’m working on a checkbox table that compares to another table and automatically checks if it exists. The functionality is all good, but as soon as I add ngModel to save the changes, the initial check seems to be ...