针对固定定位/绝对定位元素实现水平垂直居中的方法

117 阅读1分钟

知道具体宽度情况下

水平居中位置:(总宽度 - 元素宽度) / 2
垂直居中位置:(总高度 - 元素高度) / 2

不明确具体宽度情况下

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fixed Element Centering</title>
<style>
  .fixed-element {
    position: fixed;
    width: 200px;
    height: 200px;
    background-color: pink;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    /* 假设您有其他样式 */
  }
</style>
</head>
<body>

<div class="fixed-element">This is a fixed element.</div>

<script>
  // 获取浏览器窗口的宽度
  const windowWidth = window.innerWidth;

  // 设置固定定位元素的left属性
  document.querySelector('.fixed-element').style.left = `${windowWidth / 2}px`;
</script>

</body>
</html>