我想在可滚动的 div 中居中放置一个元素。这样当我加载组件时,所选的 div 位于 div 的中心。 我已经尝试给元素一个唯一的 ID 并通过 CSS 将其居中,但没有结果。
组件.html
<div class="scrollmenu">
<a *ngFor="let a of af" (click)="selected(a, 'af')"
[ngStyle]="{backgroundColor: a==selectedValue.af ? 'grey' : ''}">
{{a}}
</a>
</div>
组件.css
div.scrollmenu {
background-color: #333;
overflow: auto;
white-space: nowrap;
}
div.scrollmenu a {
display: inline-block;
color: white;
text-align: center;
padding: 14px;
text-decoration: none;
}
html {
scroll-behavior: smooth;
}
组件.ts
selected(waarde: any, param: string) {
this.selectedValue[param] = waarde;
}
在此示例中,我想将数字 50 置于可滚动 div 的中心。
最佳答案
主要技巧是将元素放入 View,然后将 inline
参数传递给 center。如果可能,请始终为循环中的元素提供唯一 ID。
document.getElementById('50').scrollIntoView({behavior: "smooth", inline: "center"});
阅读MDN docs
document.getElementById('40').scrollIntoView({behavior: "smooth", inline: "center"});
div.scrollmenu {
background-color: #333;
overflow: auto;
white-space: nowrap;
}
div.scrollmenu a {
display: inline-block;
color: white;
text-align: center;
padding: 14px;
text-decoration: none;
}
div.scrollmenu a:hover {
background-color: #777;
}
<div id="horizontalScroll" class="scrollmenu">
<a id="0" >0</a>
<a id="5" >5</a>
<a id="10" >10</a>
<a id="15" >15</a>
<a id="20" >20</a>
<a id="25" >25</a>
<a id="30" >30</a>
<a id="35" >35</a>
<a id="40" >40</a>
<a id="45">45</a>
<a id="50" >50</a>
<a id="55" >55</a>
<a id="60" >60</a>
<a id="65" >65</a>
<a id="70" >70</a>
</div>
在 StackBlitz 上查看此内容
关于html - 可滚动 div 中的中心元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60631162/