当它位于另一个具有90%宽度的div内时,如何使div占据页面的整个宽度? [英] How can I make a div take the full width of the page when it is inside another div that have 90% width

查看:135
本文介绍了当它位于另一个具有90%宽度的div内时,如何使div占据页面的整个宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能使孩子占据整个页面的宽度

how can I make the child take the full width of the page

<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变量,您可以拥有更多动态效果:

With CSS variable you can have something more dynamic:

.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>

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

In case the container is not centered simply put all the missing margin on one side:

.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的使用不是一个好主意,因为它包括滚动的宽度.这样你就会溢出.

PS: the use of vw isn't a good idea because it includes the width of the scroll. So you will have overflow.

.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>

这篇关于当它位于另一个具有90%宽度的div内时,如何使div占据页面的整个宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆