CSS图像中心

时间:2015-02-27 12:47:07

标签: css asp.net-mvc image center centering

我使用以下代码在visual studio中工作, 但是,URL图像拒绝像h2标签那样居中在列中。 香港专业教育学院尝试了多种选择,如

  background-image: url('http://i59.tinypic.com/314uzyb.jpg');
  background-position: center center;
  background-repeat: no-repeat;

  background: url('http://i59.tinypic.com/314uzyb.jpg') center center;
  background-repeat: no-repeat;

这是目前的样子。如您所见,我的h2标签以列为中心。但是,图像仍然是左边的。 would like to center both pills to center of their columns 这是代码的完整部分:

      <div class="col-md-4">
    <h2 style="text-align: center;">Version 1.0</h2>

    @*EDIT________________BUTTON1 THAT TAKES USER TO A CREATE PAGE FOR SPECIFIC SONG TYPE(KEY)*@
    <style type="text/css">
        .urlImg1 {
            width: 200px;
            height: 200px;
            display: block;
            background-image: url('http://s28.postimg.org/3jrpa5hvx/BUTTON1_A.jpg');
            background-repeat: no-repeat;
        }

            .urlImg1:hover {
                background-image: url('http://s13.postimg.org/brbfy86xz/BUTTON1_B.jpg');
            }
    </style>
    <a href="http://www.corelangs.com" class="urlImg1" title="Corelangs link"></a>
    @*END BUTTON#1_____________________________________*@
</div>

<div class="col-md-4">
    <h2 style="text-align: center;">Version 2.0</h2>

    @*EDIT________________BUTTON2 THAT TAKES USER TO A CREATE PAGE FOR SPECIFIC SONG TYPE(KEY)*@
    <style type="text/css">
        .urlImg2 {
            width: 200px;
            height: 200px;
            display: block;
            background-image: url('http://i59.tinypic.com/314uzyb.jpg');
            background-repeat: no-repeat;
        }

            .urlImg2:hover {
                background-image: url('http://i60.tinypic.com/rmp4pv.jpg');
            }
    </style>
    <a href="http://www.corelangs.com" class="urlImg2" title="Corelangs link"></a>
    @*END BUTTON#2_____________________________________*@
</div>

2 个答案:

答案 0 :(得分:2)

这是因为你试图使图像居中,而元素和图像一样宽。换句话说,图像居中,只是元素与图像一样宽,使其看起来不居中。

<强>实施例

http://jsfiddle.net/ey0upzw1/

width: 500px; /* Equal to col width */

http://jsfiddle.net/ey0upzw1/1/

width: 200px; /* Not equal to col width */

<强>解决方案

将图像设置为margin: auto

text-align: center添加到col-4而不是仅添加到h2,您还必须将图片设置为inline-block而不是block

答案 1 :(得分:0)

您需要将链接置于中心位置。

由于它具有已定义的宽度,因此您可以使用margin:auto

执行此操作

.urlImg1 {
  width: 200px;
  height: 200px;
  display: block;
  background-image: url('http://s28.postimg.org/3jrpa5hvx/BUTTON1_A.jpg');
  background-repeat: no-repeat;
  margin: auto;
}
.urlImg1:hover {
  background-image: url('http://s13.postimg.org/brbfy86xz/BUTTON1_B.jpg');
}
<div class="col-md-4">
  <h2 style="text-align: center;">Version 1.0</h2>
  <a href="http://www.corelangs.com" class="urlImg1" title="Corelangs link"></a>
</div>