,我正试图通过使用三分法则使我的网站看起来像赃物。

我有一堆相当高的东西,我想将视口高度距离浏览器窗口顶部的距离的三分之一定位。

所以这就是我应该做的事情,但是没有用:

div {
  display: block;
  margin-top: 33vh; /* maybe margin-top: 33%; but that seemed to be worse */
  margin-left: auto;
  margin-right: auto;
  width: 50rem;
  transform: translate(0, -50%); /* To compensate for the divs own height */

  position: relative; /* Not relavent to this situation but might be causing problems? */
}


我认为特别是

transform: translate(0, -50%);


工作不正常。

谢谢您的帮助!

最佳答案

如果我正确理解您的需求,最好的解决方案就是使用JavaScript。

对于JavaScript部分,您需要执行以下操作:

<script>
var vHeight = window.innerHeight; // get viewport height value
var vHeight3rd = vHeight/3; // get a 3rd of the viewport height value
$('div').css({position: 'absolute', marginTop: -(vHeight3rd)}); // assign a negative top margin of the 1/3rd value to position

// add for when resizing browser, value will be adjusted accordingly.
window.addEventListener('resize', function(){
    var vHeight = window.innerHeight; // get viewport height value
    var vHeight3rd = vHeight/3; // get a 3rd of the viewport height value
    $('div').css({position: 'absolute', marginTop: -(vHeight3rd)}); // assign a negative top margin of the 1/3rd value to position
});
</script>


我尚未测试上述解决方案。但是它应该按照您需要的方式工作。我的解决方案使用的是jQuery,因此请确保将库添加到您的解决方案中。

关于css - 将Div定位为视口(viewport)高度的三分之一,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28801648/

10-09 18:45