preface
Positioning is familiar and is often used when building pages. So if you look at the headline and you know what I’m talking about it’s not necessarily targeted relative to the browser. Of course, this is just a small point, I did not know this small point, if you do know, then skip this article.
Practice a
Simply write a centered box on the page to see how it looks.
<head>
<style>
body {
background: gray;
}
.box {
width: 200px;
height: 200px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: blue;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
Copy the code
So far, so good.
So let’s put another box inside this box. And fixed?
<head>
<style>
body {
background: gray;
}
.box {
width: 200px;
height: 200px;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: blue;
}
.box-inside {
width: 100px;
height: 100px;
position: fixed;
top: 0;
left: 0;
background: red;
}
</style>
</head>
<body>
<div class="box">
<div class="box-inside"></div>
</div>
</body>
Copy the code
Oh ho! ? What’s going on here? Inside the box set top: 0; Left: 0 but is based on the outer box positioning. Can fixed layouts not be nested?
Reacquainted
If you have any questions, be sure to refer to MDN Web Docs and re-learn.
You can see that.fixed
In which he said:
When the element ancestor’s transform, Perspective, or filter attribute is not None, the container changes its viewport to that ancestor
So let’s do that demo again
.box {
width: 200px;
height: 200px;
position: fixed;
top: calc(50% - 100px);
left: calc(50% - 100px);
background: blue;
}
Copy the code
This has achieved the original desired effect!
At the end
Let me get a moon cake T^T