Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: I can't put a button in the middle of a DIV element

Tags:

css

button

I'm using CSS buttons from this tutorial:

http://www.oscaralexander.com/tutorials/how-to-make-sexy-buttons-with-css.html

I need to put a button in the middle of a DIV so it's centered. But I can't!

Here's the code of the button:

<a class="button" href="#"><span>Bring world peace</span></a>  

And here's CSS:

.clear { /* generic container (i.e. div) for floating buttons */
    overflow: hidden;
    width: 100%;
}

a.button {
    background: transparent url('bg_button_a.gif') no-repeat scroll top right;
    color: #444;
    display: block;
    float: left;
    font: normal 12px arial, sans-serif;
    height: 24px;
    margin-right: 6px;
    padding-right: 18px; /* sliding doors padding */
    text-decoration: none;
}

a.button span {
    background: transparent url('bg_button_span.gif') no-repeat;
    display: block;
    line-height: 14px;
    padding: 5px 0 5px 18px;
} 

Here's the code I'm trying to use:

<div align="center"><a class="button" href="#"><span>Bring world peace</span></a></div>
like image 281
Alex Avatar asked Jul 24 '10 12:07

Alex


People also ask

Why is my button not centering HTML?

A button is an inline element by default, so you can center it by adding a container div around the button and give that container a text-align: center property to align the button correctly. The margin: 0 auto only works when your element is a block-level element.

Why are my divs not centering?

You can't center divs with margin: 0 auto; if you have not set width to element. Add width to . top-center to make it work.


2 Answers

Modify the button class for these properties:

.button{
  margin-left:50%;
  margin-right:50%;
  position: relative;
}

And wrap your link in the div like this:

<div align="center">
  <a class="button" href="#"><span>Bring world peace</span></a>  
</div>
like image 79
Sarfraz Avatar answered Oct 15 '22 07:10

Sarfraz


the align attribute for the div element is deprecated. You're better off defining a class for that div, like so:

<div class="centerize">
  <a class="button" href="#"><span>Bring world peace</span></a>
</div>

And the CSS:

.centerize { 
    text-align: center;
}

Note however that setting the text-align will only affect the content inside the div. The div itself (should be) a block element, and depending on where it sits in the document structure, may not be centered itself.

Just to make a little more certain, you can do something like this:

.centerize {
    display: block;
    margin: 0 auto;
    text-align: center;
}

Now you can apply centerize to any element, and that element should take up the entire browser's width and center-align its content.

like image 36
Chris Avatar answered Oct 15 '22 06:10

Chris