首页 > 解决方案 > 为什么这个 div 会低于页面的 50% 而不是直接到中心?

问题描述

.try {
    background-color: aqua;
    width: 100px;
    height: 100px;
    margin: 0 auto;
    margin-top: 50%;
    position:relative;
}
<div class="try"></div>

您好,很抱歉提出一个愚蠢的问题,但是是否可以在不使用 flexbox 的情况下让这个 div 进入页面的中心?

标签: htmlcss

解决方案


您需要在 css insted of margin-top 中设置 top 和 transform 属性。

top: 50%;
transform: translateY(-50%);

.try {
  background-color: aqua;
  width: 100px;
  height: 100px;
  margin: 0 auto;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

body,
html {
  height: 100%;
}
<div class="try"></div>


推荐阅读