[英]Question with CSS horizontal bar and div borders not aligning
您可以在这些屏幕截图中看到
我有两个问题:
这是演示:
.app{ height:100%; width: 100%; } html, #root, body{ height:100%; margin:0px; } .header{ height: 50px; width:100%; border:1px solid green; } .app-body{ display: flex; height: calc(100% - 55px); } .menu{ height:100%; border:1px solid green; width:100px; } .content{ flex:1; height:100%; border:1px solid orange; }
<div class="app"> <div class="header"></div> <div class="app-body"> <div class="menu"></div> <div class="content"></div> </div> </div>
要修复水平滚动条,应使用box-sizing: border-box
属性。 框大小定义了width属性包含的内容。 值box-sizing
表示宽度包括边框宽度和填充。
添加框大小后的CSS。
.app{
height:100%;
width: 100%;
box-sizing: border-box;
}
html, #root, body{
height:100%;
margin:0px;
}
.header{
height: 50px;
width:100%;
border: 1px solid green;
box-sizing: border-box;
}
.app-body{
display: flex;
height: calc(100% - 55px);
}
.menu{
height:100%;
border:1px solid green;
width:100px;
}
.content{
flex:1;
height:100%;
border:1px solid orange;
}
欢迎来到SO!
那是因为您需要添加box-sizing: border-box
。
根据Mozilla MDN :
border-box告诉浏览器在为元素的宽度和高度指定的值中考虑任何边框和填充。 如果将元素的宽度设置为100像素,则该100像素将包括您添加的任何边框或填充,内容框将缩小以吸收该额外宽度。 通常,这使调整元素大小变得容易得多。
看这个演示:
.header, .menu, .content { box-sizing: border-box; } .app{ height:100%; width: 100%; } html, #root, body{ height:100%; margin:0px; } .header{ height: 50px; width:100%; border:1px solid green; } .app-body{ display: flex; height: calc(100% - 55px); } .menu{ height:100%; border:1px solid green; width:100px; } .content{ flex:1; height:100%; border:1px solid orange; }
<div class="app"> <div class="header"></div> <div class="app-body"> <div class="menu"></div> <div class="content"></div> </div> </div>
要了解会发生什么,您需要知道默认情况下元素的大小由其内容决定。
例如,如果我们有一个div(默认情况下div是一个块,因此它具有100%的宽度)并在其周围添加1px边框,那么将发生的情况是div的宽度增加了2px,因为正如我提到的那样之前-元素由其元素(框)确定大小。 为了避免这种情况,我们可以告诉浏览器我们不想按其内容来调整元素的大小。 我们可以告诉浏览器我们要将其大小设置为border-box
,当我们在添加padding / border时向元素添加其他像素时,宽度不会重叠。
在您的示例中,标头是div(意味着宽度为100%),并且具有附加边框(左侧边框为+1,右侧边框为+1),总计为100%+ 2px宽度。
您的.header
具有同级.app-body
。 应用程序主体也是一个块,因此具有100%的宽度。 与标头不同, .app-body
没有边框,因此总宽度为100%。
.app-body
有2个孩子。 他们两个都有边界。 您可能会问自己,他们如何影响父母。 好吧,这是因为他们的父母是一个街区,并且不会受到孩子的影响。 这就是为什么他的孩子不影响他的宽度的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.