提问者:小点点

我如何使我的形象固定在中心?


我有一个问题的图像,我试图变小,当我向下滚动。直到现在我得到了这个,它工作得很完美,除了事实,当我向下滚动图像变得更小到图片的左上角,而不是中间。这样图像就不会停留在中心。有没有什么办法让我把图像保持在中间或者以某种方式改变锚点到中心?

null

// When the user scrolls down 50px from the top of the document, resize the header's font size
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    document.getElementById("logohome").style.height = "15%";
    document.getElementById("logohome").style.width = "15%";
  } else {
    document.getElementById("logohome").style.height = "40%";
    document.getElementById("logohome").style.width = "40%";
  }
}
#logohome{
    position: fixed;
    top: 0;
    left: 43%;
    width: 35%;
    transform: translate(0%, 0%);
    transition: 0.2s;
    
}
<div id="logohome">
  <img src="img/logosmallbrown.png" width="50%" height="50%">
</div>

null


共3个答案

匿名用户

有必要吗?

null

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
      document.getElementById("logohome").style.width = "15%";
      document.getElementById("logohome").style.left = "42%";
  } else {
      document.getElementById("logohome").style.width = "35%";
      document.getElementById("logohome").style.left = "32%";
  }

}
body {
    height: 3000px;
}

#logohome{
    position: fixed;
    top: 0;
    left: 32%;
    width: 35%;
    transform: translate(0%, 0%);
    transition: 0.2s;
    text-align: center;
}
<div id="logohome">
       <img src="https://static3.depositphotos.com/1000992/133/i/450/depositphotos_1337508-stock-photo-a-free-flying-white-dove.jpg" width="50%" height="50%">
</div>

匿名用户

您可以通过以下代码完成此操作:

img{
   position: fixed;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

匿名用户

先用标签包装标签,然后让标签从标签继承集中属性。这是HTML的代码,修改它。

<div>
Sample Text
<span style="text-align: center;"><img src="file_path_here"></span>
<!--Now you can put stuff here-->
</div>