按钮中心

通常的 CSS 中心问题,只是不适合我,问题是我不知道完成的宽度像素

我有一个 div 为整个导航,然后每个按钮内,他们不再中心,当有一个以上的按钮。:(

.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>

非常感谢你的帮助,谢谢


结果

如果宽度是未知的,我确实找到了一种方法,一个中心的按钮,不完全高兴,但没关系,它的工作: D

最好的办法是把它放在桌子上

<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>
559425 次浏览

The problem is with the following CSS line on .nav_button:

margin: 0 auto;

That would only work if you had one button, that's why they're off-centered when there are more than one nav_button divs.

If you want all your buttons centered nest the nav_buttons in another div:

<div class="nav">
<div class="centerButtons">
<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>
</div>

And style it this way:

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


/* Centers the div that nests the nav_buttons */
.centerButtons {
margin: 0 auto;
float: left;
}


.nav_button{
height:34px;
margin-right:10px;
float: left;
}

I realize this is a very old question, but I stumbled across this problem today and I got it to work with

<div style="text-align:center;">
<button>button1</button>
<button>button2</button>
</div>

Cheers, Mark

when all else fails I just

<center> content </center>

I know its not "up to standards" any more, but if it works it works

Another nice option is to use :

width: 40%;
margin-left: 30%;
margin-right: 30%

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";