如何在HTML中使用Thymeleaf变量为按钮设置CSS的top属性
实现方法
- 方法1:直接在元素标签上通过
th:style属性设置,适合单个元素单独指定样式的场景
<!-- 假设positionIndex.x的单位为px,直接拼接即可 --> <button th:style="|top: ${positionIndex.x}px|" type="button">测试按钮</button> <!-- 如果需要设置默认值避免变量为空导致样式异常,可以写为 --> <button th:style="|top: ${positionIndex.x?:0}px|" type="button">测试按钮</button>
- 方法2:在CSS样式块中通过Thymeleaf CSS内联设置,适合多个元素共用该动态样式的场景
<!-- 先给style标签添加th:inline="css"属性 --> <style th:inline="css"> .dynamic-position-btn { /* 双中括号包裹的变量会被Thymeleaf自动解析替换,外层注释是为了避免本地IDE报CSS语法错误,不影响运行 */ top: /*[[${positionIndex.x}]]*/ 0px; } </style> <!-- 给按钮加上对应的类名即可 --> <button class="dynamic-position-btn" type="button">测试按钮</button>
注意:如果
positionIndex.x变量本身已经包含CSS单位,上面示例中的px后缀可以直接去掉,避免重复设置单位导致样式失效。
内容的提问来源于stack exchange,提问作者Ko Jung hoon
相关产品推荐
相关产品推荐

