Html 如何使用 CSS 将微调器设置在屏幕中间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25829856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:42:12  来源:igfitidea点击:

How to set a spinner into the middle of the screen with CSS?

htmlcss

提问by Josh Crozier

i need some CSS help, i have a spinner for the loading page, centered totally, it is centered vertically, but now how can i center that spinner for all possible screen widths?

我需要一些 CSS 帮助,我有一个用于加载页面的微调器,完全居中,垂直居中,但现在我如何才能将所有可能的屏幕宽度的微调器居中?

This is my markup:

这是我的标记:

<!DOCTYPE html>
<html>

  ...

  <body>

    <div class="loading">
      <div class="loader"></div>
    </div>

    ...

  </body>
</html>

and this is my stylesheet:

这是我的样式表:

.loading {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 9999999999;
  overflow: hidden;
  background: #fff;
}
.loader {
  font-size: 10px;
  border-top: .8em solid rgba(218, 219, 223, 1);
  border-right: .8em solid rgba(218, 219, 223, 1);
  border-bottom: .8em solid rgba(218, 219, 223, 1);
  border-left: .8em solid rgba(58, 166, 165, 1);
  -webkit-animation: load8 1.1s infinite linear;
  animation: load8 1.1s infinite linear;
}
.loader,
.loader:after {
  border-radius: 50%;
  width: 8em;
  height: 8em;
  display: block;
    position: absolute;
    top: 50%;
    margin-top: -4.05em;
}

回答by Josh Crozier

Since the element has a fixed width of 8em, you could add left: 50%and then displace half of the element's width using margin-left: -4px:

由于元素的固定宽度为8em,您可以添加left: 50%然后使用以下方法替换元素宽度的一半margin-left: -4px

Updated Example

更新示例

.loader {
  left: 50%;
  margin-left: -4em;
}

If the dimensions of the element aren't fixed and known in advance, see my other answer for alternative options.

如果元素的尺寸不是固定的并且事先知道,请参阅我的其他答案以获取替代选项