Button Center CSS

Viewed 553959

Usual CSS centering issue, just not working for me, the problem is that I don't know the finished width px

I have a div for the entire nav and then each button inside, they dont center anymore when there is more than one button. :(

.nav {
  margin-top: 167px;
  width: 1024px;
  height: 34px;
}

.nav_button {
  height: 34px;
  margin: 0 auto;
  margin-right: 10px;
  float: left;
}
<div class="nav">
  <div class="nav_button">
    <div class="b_left"></div>
    <div class="b_middle">Home</div>
    <div class="b_right"></div>

  </div>
  <div class="nav_button">
    <div class="b_left"></div>
    <div class="b_middle">Contact Us</div>
    <div class="b_right"></div>

  </div>
</div>

Any help would be greatly appreciated. Thanks


Result

If the width is unknown, I did find a way a center the buttons, not entirely happy but doesnt matter, it works :D

The best way is to put it in a table

<table class="nav" align="center">
    <tr>
      <td>
        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Home</div>
            <div class="b_right"></div>
        </div>

        <div class="nav_button">
            <div class="b_left"></div>
            <div class="b_middle">Contact Us</div>
            <div class="b_right"></div>
        </div>
      </td>
    </tr>
  </table>
7 Answers

Consider adding this to your CSS to resolve the problem:

button {
    margin: 0 auto;
    display: block;
}

Consider adding this to your CSS to resolve the problem:

.btn {
  width: 20%;
  margin-left: 40%;
  margin-right: 30%;
}

In HTML you can write,

<div id="btn">
<button>Click</button>
</div>

if you work with JS instead of CSS, you can write this to move the button to center.

const bu = document.getElementById("btn");
bu.style.cursor="pointer";
bu.style.justifyContent="center";
bu.style.display="flex";
Related