子元素使用position:fixed,导致他的宽度不能和父元素保持一致的解决方案

  最近在编码过程中,遇到过这样一个问题,代码如下,我们有一个父级,他有一定的宽度,在他的里面有两个子级,其中一个是绝对定位的,且要求他们的宽度都和父级保持一致,然后问题就出现了,我们会发现,有了定位的son他的宽度远远的超出了我们父级的宽度,那么问题是怎么引起的呢?

<div class="fathor" style="width:1024px">
    <div class="son" style="position:fixed;width:100%">
  </div>

  <div class="demo" style="width:100%">
  </div> </div>

  经过各种百度之后发现,原来给子元素加了position:fixed这个属性之后,他就默认相对于window去定位了,就相当与你将这个元素相对于window加上了position:absolute的属性,所以给他加百分比长度的话就是相对于window的百分比。那么解决方案有哪些呢?我们来一一尝试。

  1、left:0;right:0;因为fixed也相当于是定位的一种,所以我们当然也可以用left和right来进行定位了,然后将left的值扩大,同时将width的百分比减少,从而使得son和demo的宽度达到一致,从而起到一种视觉上的欺骗效果。(PS:请谨慎使用)

<div class="fathor" style="width:1024px;height: 500px;margin: 100px auto;">
  <div class="son" style="position:fixed;width: 76%;height: 200px;background-color: darkblue;left: 163px;right: 0;">
  </div>

  <div class="demo" style="width:100%;height: 300px;background-color: red;margin-top: 210px">
  </div>
</div>

  2、calc();关于calc的具体使用将在我后面的播客中提出,在这里,我们可以将son的width由100%改为calc(100%-324px),这里这个长度不知道是否有规律,还是要自己找,相对来说适应性就不是很好。

<div class="fathor" style="width:1024px;height: 500px;margin: 100px auto;">
  <div class="son" style="position:fixed;width: calc(100% - 324px);height: 200px;background-color: darkblue">
  </div>

  <div class="demo" style="width:100%;height: 300px;background-color: red;margin-top: 210px">
  </div>
</div>

  3、absolute改造;因为我们上面提到过,本质上说,fixed就是一个相对于window的absolute,但是absolute却可用relative来指定他相对于谁定位,所以我们在这里,可以将fixed绝对定位用absolute来进行改造。(PS:如果代码改动不大的情况下建议使用,毕竟更好控制,这种就大家自己操作了哟)

  4、给fathor加fixed属性;我们还可以给fathor加position:fixed;属性,从而让父元素也相对于window定位,同时,子元素也是相对于window的定位,所以他们就都是和window产生了联系,从而也就在一定程度上保持了一致。(PS:这种情况适用于fathor是最外层元素的情况下,否则的话fathor相对于他原来的父级的定位就需要进行重新定义了,而且很大可能会破坏原有样式)

<div class="fathor" style="width:1024px;height: 500px;margin: 100px auto;transform: scale3d(1, 1, 1);position: fixed;"> 
  <div class="son" style="position:fixed;width: 100%;height: 200px;background-color: darkblue">
  </div>

  <div class="demo" style="width:100%;height: 300px;background-color: red;margin-top: 210px">
  </div>
</div>
posted @ 2019-09-19 15:23  奈何天丶  阅读(20160)  评论(4编辑  收藏  举报