如果需要让form里的最后一个div下沉到底部,通常想到的是form div:last-child 样式,这个样式在静态页面时确实没问题,但一定运行起来后就不一定了。因为asp.net core 的Tag Helper在默认情况下会插入一个hidden的input,写入一个防止跨域访问的令牌。这时候的form实际上是
<form> <div> <button type="submit" class="btn btn-lg btn-primary" style="width:250px">提交</button> </div> <input type="hidden" name="__RequestVerificationToken" ...> </form>
这时div不再是最后一个孩子了。所以上述样式将不再起作用。
这时候要么显示地给这个div一个明确的样式,比如spacer,要么使用form > div:last-of-type。
如果使用明确的样式,代码为
<style> form .spacer { margin-top: auto; } </style> <form> <div class="spacer"> <button type="submit" class="btn btn-lg btn-primary" style="width:250px">提交</button> </div> <input type="hidden" /> </form>
如果还是要选择最后一个div,可以用
<style> form > div:last-of-type { margin-top: auto; } </style> <form > <div> <button type="submit" class="btn btn-lg btn-primary" style="width:250px">提交</button> </div> <input type="hidden" /> </form>
总结对比:
| 选择器 | 含义 | 易错程度 | 
|---|---|---|
form div:last-child | 
选 form 中是最后一个子元素的 div | 
❗容易错 | 
form > div:last-of-type | 
选 form 中最后一个 div 类型子元素 | 
✅ 更稳妥 | 
.spacer 类名 | 
显式标记你要控制的元素 | ✅ 最推荐 | 
点点滴滴...