user3355028
user3355028

Reputation: 177

Aligning HTML element using margin 0 auto

I'm trying to align the middle button which called "center" to the center of the page. I tried to use margin 0 auto with no success. Anyone know whats I'm doing wrong?

Thanks.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id=container>
    <div id="left">
      <input type="button" value="left">
    </div>

    <div id="center">
      <input type="button" value="center">
    </div>

    <div id="right">
      <input type="button" value="right">
    </div>
  </div>
</body>
</html>

and this is the css

#container {
  background-color: yellow;
}

#left, #center, #right {
  display: inline-block;
}

#center {
  background-color: red;
  width: 65px;
  text-align: center;
  margin: 0 auto;
}

#right {
  float: right;
}

Upvotes: 1

Views: 98

Answers (2)

Jacob G
Jacob G

Reputation: 14172

To center it, if there is no parent container, as you said in the comments, give #center display:block then margin: 0 auto; will work fine.

Upvotes: 2

Vitorino fernandes
Vitorino fernandes

Reputation: 15951

  • add text-align:center for the #container
  • add display:inline-block to #center so that it can be centered with parent text-align property
  • add float:left for the left button and float:right for the right button

#container {
  background-color: yellow;
  text-align: center;
}
#center {
  display: inline-block;
}
#center {
  background-color: red;
  width: 65px;
}
#right {
  float: right;
}
#left {
  float: left;
}
<div id=container>
  <div id="left">
    <input type="button" value="left">
  </div>
  <div id="center">
    <input type="button" value="center">
  </div>
  <div id="right">
    <input type="button" value="right">
  </div>
</div>

Upvotes: 5

Related Questions