html - 当一个 div 位于另一个宽度为 90% 的 div 中时,如何使它占据页面的整个宽度

标签 html css

我怎样才能让 child 占满页面的整个宽度


<div class='container'>
   <div class='child'>
            something
   </div>
</div>

.container {
    width: 90%;
    margin: 0 auto;
 }

.child {}

最佳答案

考虑负边距。

.container {
  width: 90%;
  margin: 0 auto;
  padding: 10px 0;
  background: red;
}

.child {
  height: 50px;
  background: blue;
  margin: 0 calc(-5% / 0.9); 
  /* 
    The container is taking 90% of 100% so we are missing 10%
    we plit this value on both sides (5% + 5%) and since percentage is relative
    to parent so to make the percentage inside .child relative to body
    we divide by the percentage of container
    
    it should be then 5%/0.9 or 5%*1.11
  
  */
}

body {
  margin: 0;
}
<div class='container'>
  <div class='child'>
    something
  </div>
</div>

使用 CSS 变量,您可以拥有更动态的内容:

.container {
  width: calc(var(--s)*100%);
  margin: 5px auto;
  padding: 10px 0;
  background: red;
}

.child {
  height: 50px;
  background: blue;
  margin: 0 calc((-50% * (1 - var(--s))) / var(--s)); 
}

body {
  margin: 0;
}
<div class='container' style="--s:0.8">
  <div class='child'>
    something
  </div>
</div>

<div class='container' style="--s:0.5">
  <div class='child'>
    something
  </div>
</div>
<div class='container' style="--s:0.2">
  <div class='child'>
    something
  </div>
</div>

如果容器没有居中,只需将所有缺失的边距放在一侧:

.container {
  width: calc(var(--s)*100%);
  margin: 5px 0;
  padding: 10px 0;
  background: red;
}

.child {
  height: 50px;
  background: blue;
  margin-right:calc((-100% * (1 - var(--s))) / var(--s)); 
}

body {
  margin: 0;
}
<div class='container' style="--s:0.8">
  <div class='child'>
    something
  </div>
</div>

<div class='container' style="--s:0.5">
  <div class='child'>
    something
  </div>
</div>
<div class='container' style="--s:0.2">
  <div class='child'>
    something
  </div>
</div>

PS:vw 的使用不是一个好主意,因为它包含滚动条的宽度。所以你会溢出。

.box {
  height:50px;
  background:red;
  width:100vw;
  border:5px solid green;
  box-sizing:border-box;
}

body {
 margin:0;
 min-height:200vh;
}
<div class="box"></div>

关于html - 当一个 div 位于另一个宽度为 90% 的 div 中时,如何使它占据页面的整个宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56685563/

相关文章:

css - Bootstrap 中可用的文本颜色类

javascript - 在网络上编辑图片并导出为图像

javascript - 我无法发现我的基本错误。 JS 和 HTML

javascript - 在 dom 中,html 元素和片段之间的功能区别是什么?

javascript - 如何根据属性值在表中显示信息 (XML-XSLT)

jquery - 将 JSON 解析为 HTML 表 : How do I format the css of the table?

html - 将背景图像与 DOCTYPE 一起使用

html - 导航链接的背景图片

javascript - 使用新文本更新占位符文本 onClick/onFocus

jquery - 使用 Jquery 触发悬停效果