微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

css – 当应用position:fixed时,是否可以保留父元素的宽度?

当我们应用位置:固定到一个元素,它取为文档的 out of the normal flow,因此它不尊重它的父元素宽度。
有没有办法使它继承它的父宽度,如果这被声明为一个百分比? (下面的工作用例)
let widthis = $('.Box').width();
$('.dimensions').text(`width is ${widthis}`);

$('button').on('click',function() {
  $('.Box').toggleClass('fixed');
  let widthis = $('.Box').width();
  $('.dimensions').text(`width is ${widthis}`);
});
.container {
  max-width: 500px;
  height: 1000px;
}

.Box {
  background-color: lightgreen;
}

.fixed {
  position: fixed;
}

.col-1 {
  border: 1px solid red;
  float: left;
  width: 29%;
}

.col-2 {
  border: 1px solid pink;
  float: left;
  width: 69%;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click this to toggle position fixed for the left column</button>
<div class="container">
  <div class="col-1">
    <div class="Box">
      fixed content<br>
      <span class="dimensions"></span>
    </div>
    </div>
  
  <div class="col-2">
    some other content
    </div>
  </div>

解决方法

可以使用width:inherit。这将使它听父母。我测试它,它在Firefox中工作。

原文地址:https://www.jb51.cc/css/219696.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。