如何在页面居中按钮?已试margin:auto无效,求解决方案
Hey there! Let's get that button centered properly—no guesswork with percentages required. The issue with margin: auto not working boils down to one key detail: buttons are inline-block elements by default, and margin: auto only applies to block-level elements that have a defined width (or a parent container that constrains their available space).
Here are a few straightforward solutions that play nice with Bootstrap and Pure Grids:
Solution 1: Use Bootstrap's Built-in Text Centering Class
This is the easiest fix if you're already using Bootstrap. Just wrap your button in a parent container with the text-center class—since buttons are inline-block, this will center them horizontally automatically:
<div class="text-center"> <button class="btn btn-primary">Your Button</button> </div>
Solution 2: Make the Button a Block Element (For margin: auto to Work)
If you want to stick with margin: auto, convert the button to a block-level element and set its width to fit its content (so it doesn't stretch full-width). You can do this with custom CSS or inline styles:
Inline Style Example:
<button class="btn btn-primary" style="display: block; margin-left: auto; margin-right: auto; width: fit-content;"> Your Button </button>
Custom CSS Class Example:
.centered-btn { display: block; margin-left: auto; margin-right: auto; width: fit-content; }
Then apply it to your button:
<button class="btn btn-primary centered-btn">Your Button</button>
Solution 3: Pure Grids Compatibility
If you're using Pure's grid system, ensure your button's parent grid container takes up the full width of its space, then use either the Bootstrap text-center class or the block-element + margin: auto method above. For example:
<div class="pure-g"> <div class="pure-u-1 text-center"> <!-- Full-width grid column --> <button class="btn btn-primary">Your Button</button> </div> </div>
Quick Note:
Make sure the parent element of your button is a block-level element (like a div) that spans the full width you want the button centered within—if the parent is narrow or inline, centering won't work as expected.
内容的提问来源于stack exchange,提问作者Robert Abovian

