Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does fixed position work when put it inside a relative position

According to this statement:

When position is set to absolute or fixed, the left property specifies the distance between the element's left edge and the left edge of its containing block. (The containing block is the ancestor to which the element is relatively positioned.)

I put a fixed element inside a relative element, and set its 'left' property to some value.This value should relative to its parent div. But it doesn't work as expected. see my codepen: https://codepen.io/iamnotstone/pen/PgdPrJ?&editable=true

The text should inside the red box.

body {
  width: 500px;
  height: 1400px;
  margin: 0 auto;
}

.test {
  width: 500px;
  height: 132px;
  background-color: red;
  position: relative;
  left: 200px
}

h1 {
  position: fixed;
  top: 0px;
  width: 500px;
  margin: 0 auto;
  padding: 10px;
  left: 0px
}
<div class='test'>
  <h1>Fixed positioning</h1>
</div>
like image 513
欧阳维杰 Avatar asked Mar 18 '26 09:03

欧阳维杰


1 Answers

According to the doc: Fixed positioning

Fixed positioning is similar to absolute positioning. The only difference is that for a fixed positioned box, the containing block is established by the viewport.

Instead of left you can use margin-left property:

body {
  width: 500px;
  height: 1400px;
  margin: 0 auto;
}
.test{
  width: 500px;
  height: 132px;
  background-color: red;
  position: relative;
  left: 200px
}


h1 {
  position: fixed;
  top: 0px;
  width: 500px;
  margin: 0 auto;
  padding: 10px;
  margin-left: 0px
}
<div class='test'>
  <h1>Fixed positioning</h1>
</div>
like image 66
Mamun Avatar answered Mar 20 '26 21:03

Mamun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!