当我们应用于position:fixed
一个元素时,它会脱离文档的正常流程,因此它不尊重它的父元素宽度。如果将其声明为百分比,有没有办法让它继承它的父宽度?(下面的工作用例)
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>