Search code examples
htmlcsscss-floatpaddingcentering

How to have equal padding on both side of a div. CSS


I have this element:

<div class="menubar">
    <a href="http://home.com"><img src="../img/home_button.png"/></a>
    <a href="http://home.com/a"><img src="../img/a_button.png"/></a>
    <a href="http://home.com/b"><img src="../img/b_button.png"/></a>
    <a href="http://home.com/c"><img src="../img/c_button.png"/></a>
</div>

My goal is to have the content of the menubar div being centered.

Using display: table; and margin:auto; achieves that but the background image I am using is cropped to fit only the div's content:

.menubar {
    display: table;
    margin: auto;
    background-image:url(/img/menubar_background.png);
}

So then, I have this other version that adds 50% padding to both sides, but the problem is that the total width of the result is 100% + the width of the buttons.

.menubar {
    padding-right:50%;
    padding-left:50%;
    background-image:url(/img/menubar_background.png);
}

I achieve something closer by using max-width:960px (100%) but there's still a problem: It doesn't actually apply the same amount of padding to both side. It ends up padding 50% to the left and whatever is left to reach 960px to the right.

Any help welcomed!


Solution

  • Use text-align instead.

    .menubar {
      text-align:center;
      background-image:url(/img/menubar_background.png);
    }