效果展示
前:
后:
未实现前代码
<template><view class="container"><view class="centered-element">我是要被居中的元素</view></view>
</template><script>export default {data() {return {title: 'Hello'}},onLoad() {},methods: {}}
</script><style>.container{border:1px solid black;height:300px;}.centered-element{border:1px solid red;}
</style>
方法一:使用Flexbox布局
核心代码
.container {display: flex;align-items: center;
}
补充:水平居中justify-content: center;
完整代码
<template><view class="container"><view class="centered-element">我是要被居中的元素</view></view>
</template><script>export default {data() {return {title: 'Hello'}},onLoad() {},methods: {}}
</script><style>.container{border:1px solid black;height:300px;display: flex; align-items: center;}.centered-element{border:1px solid red;}
</style>
方法二:使用position和transform属性
核心代码
.container {position: relative;
}.centered-element {position: absolute;top: 50%;transform: translateY(-50%);
}
完整代码
<template><view class="container"><view class="centered-element">我是要被居中的元素</view></view>
</template><script>export default {data() {return {title: 'Hello'}},onLoad() {},methods: {}}
</script><style>.container {border: 1px solid black;height: 300px;position: relative;}.centered-element {border: 1px solid red;position: absolute;top: 50%;transform: translateY(-50%);}
</style>
方法三:使用table-cell布局
核心代码
.container {display: table;height: 100%;
}.centered-element {display: table-cell;vertical-align: middle;
}
完整代码
<template><view class="container"><view class="centered-element">我是要被居中的元素</view></view>
</template><script>export default {data() {return {title: 'Hello'}},onLoad() {},methods: {}}
</script><style>.container {border: 1px solid black;height: 300px;width:100%;display: table;}.centered-element {border: 1px solid red;display: table-cell;vertical-align: middle;}
</style>