mahesh
mahesh

Reputation: 135

How to horizontally center the buttons in a fixed sized div?

Below is the code, two buttons in one div.

<div style="position:relative; width: 300px; height: 30px; border: 1px solid;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
</div>

How to horizontally center the buttons in fixed sized did ?

Upvotes: 8

Views: 22886

Answers (4)

Shailender Arora
Shailender Arora

Reputation: 7778

Give text-align:center; to your main div & don't need to use inline css we should define css classes through external CSS files and here we don't need any kind of positioning we can do easily by simple CSS

**CSS**

  div {
  width: 300px; 
  height: 30px; 
  border: 1px solid; 
  text-align:center;
  }
  .button {
   width: 70px; 
   height: 30px;
  }

HTML

<div>
<input type="button" value="ok" class="button">
<input type="button" value="ok" class="button">
</div>

demo :- http://jsbin.com/evomik/10/edit

Upvotes: 0

andyb
andyb

Reputation: 43823

Adding text-align:center; CSS to the <div> will center the buttons. You should also consider separating the style from the content, which amongst other reasons, reduces the duplication. For example

CSS

div {
    position:relative;
    width:300px;
    height:30px;
    border:1px solid;
    text-align:center;
}

input {
    position:relative;
    width:70px;
    height:30px;
}

HTML

<div>
    <input type="button" value="ok"/>
    <input type="button" value="ok"/>
</div>

Edit: The official definition for text-align states:

The text-align property describes how inline-level content of a block container is aligned

so it will centre all inline level elements and <input> is an inline element.

Upvotes: 18

dimmat
dimmat

Reputation: 195

Try this:

<div style="position:relative; width: 300px; height: 30px; border: 1px solid; text-align:center;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
</div>

Upvotes: 1

xholicka
xholicka

Reputation: 173

<div style="position:relative; width: 300px; height: 30px; border: 1px solid;">
<div id="button_container" style="margin-left:auto; margin-right:auto;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
<input type="button" value="ok" style="position:relative; width: 70px; height: 30px;">
</div>
</div>

Upvotes: -1

Related Questions