首页 > 解决方案 > 有没有办法计算居中 div 和屏幕边缘之间的宽度?

问题描述

有没有办法计算居中 div 和屏幕边缘之间的宽度?请查看照片以获得更好的理解。示例截图

标签: css

解决方案


更新

我从您的评论中看到您正在寻找一种纯 CSS 方式来执行此操作。不幸的是,这对于 Vanilla CSS 是不可能的。下面的 JavaScript 方法仍然是你最好的选择。

原来的

因此,假设您正在寻找 JavaScript,以下是您正在寻找的函数:

Element.getBoundingClientRect()

您可以阅读有关此功能如何在MDM Web Docs上工作的更多信息

基本上,你给它一个要查看的元素,它会返回一个 JS 对象,其中包含你需要的所有参数(即 x、y、宽度、高度、顶部、底部、左侧和右侧)

这是一个例子:

let elem = document.querySelector('div');
let rect = elem.getBoundingClientRect();

let text = document.querySelector('p');

let str = 
    "X: " +
    rect.x + "px, Y: " + 
    rect.y + "px\nWidth: " + 
    rect.width + "px, Height: " + 
    rect.height + "px\nTop: " + 
    rect.top + "px, Bottom: " + 
    rect.bottom + "px\nRight: " + 
    rect.right + "px, Left: " + 
    rect.left + "px";

text.innerText = str;
body {
  margin: 0;
  height: 100vh;
  display: grid;
  place-items: center;
  
  font-family: "Segoe UI Variable Display", system-ui, ui-rounded, sans-serif;
}

div {
  width: 75vw;
  height: 75vh;
  background-color: #8CB0C8;
  border: 2px solid #688394;
  border-radius: 32px;
  display: grid;
  place-items: center;
}

p {
  text-align: center;
  font-size: 16px;
  font-weight: 500;
}
<div>
  <p>This is our div!</p>
</div>

我希望这会有所帮助,请查看Stack Overflow 指南最小的、可重现的示例大纲


推荐阅读