我知道如何保持元素居中,但是现在我希望在放大时整个页面居中(即,水平滚动条应该在中间)。现在,滚动条在放大时位于最左端。
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 100%;
height: 100%;
margin: 0 auto;
}
#p {
width: 100%;
display: flex;
justify-content: space-around;
align-items: center;
}
.c1,
.c2,
.c3 {
margin: 1rem;
min-width: 15rem;
height: 5rem;
text-align: center;
}
.c1 {
background-color: red;
}
.c2 {
background-color: green;
}
.c3 {
background-color: blue;
}
<div id="p">
<div class="c1">
aaa
</div>
<div class="c2">
bbb
</div>
<div class="c3">
ccc
</div>
</div>
您可以看到当放大到一定程度时,红色div
将不在视野范围内,并且无法到达。
答案 0 :(得分:0)
只有CSS才能做到这一点。您可以考虑使用Javascript。
const container = document.querySelector("#p");
const centerEl = document.querySelector(".center-element");
container.scrollLeft = centerEl.offsetLeft + centerEl.offsetWidth / 2 - container.offsetWidth / 2;
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 100%;
height: 100%;
margin: 0 auto;
}
#p {
width: 100%;
display: flex;
/* removed:
justify-content: space-around;
align-items: center;
*/
overflow-x: scroll; /* added. so that it does not affect the whole page. */
}
.c1,
.c2,
.c3 {
margin: 1rem;
min-width: 15rem;
height: 5rem;
text-align: center;
}
.c1 {
background-color: red;
}
.c2 {
background-color: green;
}
.c3 {
background-color: blue;
}
<div id="p">
<div class="c1">
aaa
</div>
<div class="c2 center-element">
bbb
</div>
<div class="c3">
ccc
</div>
</div>