如何让我的盒子漂浮在中央?

How do I float my box in the center?

好的,所以我尝试使用 css 元素,float: center;。但是,这是行不通的。有没有其他方法可以让我的盒子浮动在我的网页中央。顺便说一下水平居中

这是我的样式表代码:

.menubox{
    width: 45%;
    height: 13%;
    background-color: white;
    border: solid 1px white;
    box-shadow: 0px 3px 5px 1px silver;
    opacity: 0.85;
    position: fixed;
    float: center;
}

这是我的 html 代码:

<div class="menubox">

    <table align="center" class="menu">
        <tr>
            <td><a class="menu" href="index.html">Home</a></td>
            <td><a class="menu" href="about.html">About</a></td>
            <td><a class="menu" href="buy.html">Buy</a></td>
            <td><a class="menu" href="contact.html">Contact</a></td>
        </tr>
    </table>

</div>

这是它在我的网页上的样子:

My box

float:center 不存在并且 margin:auto 将无法在固定位置元素上工作。

由于元素的宽度已知,我们可以计算边距:

.menubox {
  width: 45%;
  margin-left: 27.5%;     /* 55% divided by 2 */
  position: fixed;
}

body {
  background: #000;
}
.menubox {
  width: 45%;
  margin-left: 27.5%;
  /* 55%/2 */
  height: 13%;
  background-color: white;
  border: solid 1px white;
  box-shadow: 0px 3px 5px 1px silver;
  opacity: 0.85;
  position: fixed;
}
<div class="menubox">

  <table align="center" class="menu">
    <tr>
      <td><a class="menu" href="index.html">Home</a>
      </td>
      <td><a class="menu" href="about.html">About</a>
      </td>
      <td><a class="menu" href="buy.html">Buy</a>
      </td>
      <td><a class="menu" href="contact.html">Contact</a>
      </td>
    </tr>
  </table>

</div>

或者,您可以使用变换而不是进行计算(或者如果宽度未知)。

.menubox {
  left: 50%;
  transform: translateX(-50%);
}

body {
  background: #000;
}
.menubox {
  width: 45%;
  left: 50%;
  transform: translateX(-50%);
  height: 13%;
  background-color: white;
  border: solid 1px white;
  box-shadow: 0px 3px 5px 1px silver;
  opacity: 0.85;
  position: fixed;
}
<div class="menubox">

  <table align="center" class="menu">
    <tr>
      <td><a class="menu" href="index.html">Home</a>
      </td>
      <td><a class="menu" href="about.html">About</a>
      </td>
      <td><a class="menu" href="buy.html">Buy</a>
      </td>
      <td><a class="menu" href="contact.html">Contact</a>
      </td>
    </tr>
  </table>

</div>

固定位置相对于 window 视图

您必须从 css 中删除 属性 float:center。 相反,您必须添加这两个属性

left:50%; margin-left:-22.5%;

Left:50% 属性 会将您的元素居中对齐。 比起将元素移动到其负半部分以使其完美居中