css - 父级的 100% 宽度不采用边框宽度
问题描述
.item {
box-sizing: border-box;
width: 500px;
height: 60px;
background-color: blue;
border: 20px solid red;
padding: 10px;
position: relative;
}
.child {
width: 100%;
background-color: yellow;
height: 100%;
box-sizing: border-box;
position: absolute;
top: 0;
left: 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="item">
<div class="child">
</div>
</div>
</body>
</html>
编辑:
来自:https ://www.w3.org/TR/CSS22/visudet.html#the-width-property :
对于包含块基于块容器元素的绝对定位元素,百分比是根据该元素的填充框的宽度计算的。这是从 CSS1 的一个变化,其中百分比宽度总是相对于父元素的内容框计算。
为什么会这样?我正在使用边框框,期望我得到包括边框在内的父容器宽度的 100%。有谁知道也包括边界的方法?
该.child
元素设置100%
为父元素的宽度(由于 box-sizing:border-box 属性,其宽度是内容 + 填充 + 边框的总和),但仅考虑内容 + 填充。为什么不走边界?我知道当我使用 top/left/bottom/right 属性时,定位是相对于元素的填充边缘,但是当它设置为时,孩子不应该尊重边框的宽度100%
吗?
解决方案
发生这种情况是因为该属性width
被明确定义为相对于content-box
(默认)。将父级设置box-sizing
为border-box
不会改变这种行为。
我相信克服这个问题的方法是使用outline
属性来使边界不占用空间。
请参阅下面的可能替代方案:
<!DOCTYPE html>
<html lang="en">
<style>
.item {
width: 500px;
height: 60px;
background-color: blue;
outline:20px solid red;
border:1px solid black;
padding: 10px;
position: relative;
}
.child {
width: 100%;
background-color: yellow;
height: 100%;
outline:1px solid yellow;
position: absolute;
top: 0;
left: 0;
}
</style>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div class="item">
<div class="child">
</div>
</div>
</body>
</html>
推荐阅读
- java - KafkaListener ConsumerConfig AUTO_OFFSET_RESET_DOC 最早用于多个监听器
- firebase - FLUTTER:在 Firebase 实时数据库中搜索用户
- javascript - 用 Javascript 下载 PDF 文件
- c# - Xamarin 应用程序或库中 LinkerPleaseInclude.cs 文件的含义是什么?
- .net-core - HttpContext.Session 在 ASP.NET Core 2.2 中为空
- django - 使用 nginx 制作期间的 Django 媒体文件?
- json - 如何在 ruby 上将 puppet site.pp 转换为 json?
- java - Microsoft Graph API:Java SDK-如何使用 orderby?通过 lastModifiedDateTime 对 driveItems 进行 API 调用
- android - react native 无法构建android apk。gradlew clean and ... 命令失败
- database - 从应用程序更新多个 maria 数据库实例的最佳实践