为什么我的元素始终保持中心?

时间:2015-05-08 20:03:28

标签: html css

我需要我的div和#34; splashlogo"始终保持我的文件的中心。我尝试了很多不同的东西,但不确定为什么它不起作用。有人可以帮忙吗?



.splashscreenlogo {
  position: absolute;
  top: 42%;
  left: 25%;
}

<div class="splashscreenlogo">
  <div id="splashlogo">
    <img src="logo_splashscreen.png" alt="Splashscreen logo">
  </div>
</div>
&#13;
&#13;
&#13;

6 个答案:

答案 0 :(得分:1)

你可以这样做

例如,假设您的图像高度为100像素且图像宽度为100像素,则可以将其置于此中心

<div class="splashscreenlogo">
  <div id="splashlogo">
    <img src="logo_splashscreen.png" alt="Splashscreen logo" width=655 height=138>
  </div>
</div>

.splashscreenlogo {
  position: absolute;
  top: 50%;
  left: 50%;
    margin-top: -69px;
    margin-left: -327.5px
}

Refer Fiddle

答案 1 :(得分:1)

考虑到div显示为块,您可以使用类似

的内容
<div class="splashscreenlogo">
  <center>
  <div id="splashlogo">
    <img src="logo_splashscreen.png" alt="Splashscreen logo">
  </div>
  </center>
</div>

或类似的东西

<div class="splashscreenlogo" style="text-align:center">

  <div id="splashlogo">
    <img src="logo_splashscreen.png" alt="Splashscreen logo">
  </div>

</div>

或类似的东西

<div class="splashscreenlogo" style="margin:0 auto">

  <div id="splashlogo">
    <img src="logo_splashscreen.png" alt="Splashscreen logo">
  </div>

</div>

答案 2 :(得分:1)

如果你有一个完整的启动画面,听起来就像你那样,我会使用转换技巧。

重要的是,此解决方案无需知道启动图像的大小 - 您不需要更改CSS以适应不同大小的启动图像。 < / p>

CSS非常简单 - 基本上你的左上角绝对位于50%,50%;然后将图像的一半宽度和高度转换为有效地将对象的中心移动到该窗口的中点。

&#13;
&#13;
#splashlogo {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
}


/* Page styling, ignore this */
body {
  background-color: #bada55; }
img {
  box-shadow: 6px 6px 3px rgba(0,0,0,0.25); }
&#13;
<div class="splashscreenlogo">
  <div id="splashlogo">
    <img src="http://www.placecage.com/300/300" alt="Splashscreen logo">
  </div>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

首先确保您的绝对div在相对容器内。

#splashlogo {
  position:relative;
}

.splashscreenlogo {
  position: absolute;
  width:*yourwidth*
  height:*yourheight*
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin:auto;
}

你还需要一些宽度和宽度。绝对方法的高度。

答案 4 :(得分:0)

我通常使用保证金:0自动或你也可以使用左:50%。这适用于水平居中。对于垂直居中,您可以使用top:50%或line-height。

答案 5 :(得分:0)

这会使slapshlogo在大多数情况下保持水平和垂直居中,即使在垂直重新调整大小

&#13;
&#13;
.splashscreenlogo {
  height: 300px;
  width: 300px;
  background: #fff; /*#fff for white background*/
  position: absolute;
  /*margin property shorthand notation*/
  margin: -150px 0 0 -150px;
  left: 50%;
  top: 50%;
}
#splashlogo {
  height: 100px;
  width: 100px;
  background: #fff; /*#fff for white background*/
  position: absolute;
  /*margin property shorthand notation*/
  margin: -50px 0 0 -50px;
  left: 50%;
  top: 50%;
}
&#13;
<div class="splashscreenlogo">
  <img id="splashlogo" src="http://www.clker.com/cliparts/o/i/x/2/k/G/ink-splash-with-drops-black-hi.png" alt="Splashscreen logo">
</div>
&#13;
&#13;
&#13;

<强>源: How to Center Anything With CSS