css - 有没有办法计算居中 div 和屏幕边缘之间的宽度?
问题描述
有没有办法计算居中 div 和屏幕边缘之间的宽度?请查看照片以获得更好的理解。示例截图
解决方案
更新
我从您的评论中看到您正在寻找一种纯 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 指南和最小的、可重现的示例大纲
推荐阅读
- ssl - k8s 上的 hashcrop vault:初始化 tcp 类型的侦听器时出错:加载 TLS 证书时出错:打开:没有这样的文件或目录
- php - 分组和分页不能一起工作 laravel
- swift - Swift中多个对象的单个阴影?
- azure-cosmosdb - Azure Cosmos DB MongoDB api 日期时间格式
- r - 如何使闪亮的主面板占据屏幕的整个宽度
- java - 用Java中的距离和坐标计算位置
- java - 接口作为属性?
- vue.js - 带有验证器的 vuetify 中的日期选择器
- svn - 使用 Sublime Text 作为 SVN 并排比较工具
- java - Firebase RTDB 在 Android 应用中没有响应