Callerap
Callerap

Reputation: 215

How can I center this button without using a CSS hack?

Ok so here is a blueprint of what I am trying to do and some element outlines: blueprint

Alright, so as we see I want to move the logout button to the center of the div it is in (.paper).

So this is working:

button[id="centerprofile"]{
    text-align: center;
    margin-left: 44%;
}

However, I don't like using this margin-left: 44%; hack. Without this hack, the button just stays to the left even with text-align: center;.

How can I center this button perfectly to the .paper element it is in? Here is the rest of my code:

HTML:

<body>

    <ul class="topnav">
        <li><a href="index.php"><i class="fa fa-rocket" aria-hidden="true"></i> Play</a></li>
        <li><a href="deposit.php"><i class="fa fa-btc" aria-hidden="true"></i> Deposit</a></li>
        <li><a href="#contact"><i class="fa fa-btc" aria-hidden="true"></i> Withdraw</a></li>
        <li><a href="faucet.php"><i class="fa fa-university" aria-hidden="true"></i>Faucet</a></li>
        <li><a href="#support"><i class="fa fa-life-ring" aria-hidden="true"></i>Help & Support</a></li>
        <?php echo $accountButton; ?>
        <li class='right' id="top-balance"><a href=''><?php echo "<i class=\"fa fa-btc\" aria-hidden=\"true\"></i>" . $balance . "BTC"; ?></a></li>
    </ul>

<div class="paper">
    <?php echo $contentDump; ?>
</div>
</body>

PHP $contentDump:

$contentDump =
            "
            <h2>Profile</h2>
            <p>Account balance: " . $balance . "BTC</p>
            <button id='centerprofile'>Logout</button>
            ";

CSS (.button, .paper, and button[id="centerprofile"]):

button[id="centerprofile"]{
    text-align: center;
}
button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}
.paper{
    border: 6px solid white;
    height: auto;
    margin: 20px;
    padding: 20px;
    width: auto;
    background-color: white;
    margin-left: 3%;
    margin-right: 3%;
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
    font-family: "smooth";
}

Upvotes: 4

Views: 1000

Answers (3)

Ankita Chatterjee
Ankita Chatterjee

Reputation: 165

You can use this hack:

button[id="centerprofile"]{
  display: block;
  margin: 4px auto;
}

Upvotes: 1

happymacarts
happymacarts

Reputation: 2604

The correct answer should be to center the container of the button as noted in the comment by @arbuthnott

.paper {
    text-align:center;
}

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 93003

Make it a block element so you can use auto margins to center it:

button[id="centerprofile"]{
  display: block;
  margin-left: auto;
  margin-right: auto;
}

Upvotes: 5

Related Questions