实现实现div元素和文字水平及垂直居中的方法如下:
div元素水平居中:style="margin:0 auto"
div元素垂直居中:style="padding: (外层div的高-内层div的高)/2; background-clip:content-box; "
div文字水平居中:外层div中style="text-align: center; "
div文字垂直居中:内层div中style="line-height: 外层div的高; "
具体的代码展示(下面两种方法效果相同):
写法1:
<template><div style="width: 500px; height: 300px; background-color: red; margin:0 auto; "><div style="width: 300px; height: 200px; background-color: yellow; margin:0 auto; padding: 50px; background-clip:content-box; text-align: center; "><div style="color: blue; line-height: 200px;">hello world</div></div></div></template>
写法2:
<template><div class="red_rectangle"><div class="yellow_rectangle"><div class="blue_text">hello world</div></div></div></template>
<style lang="scss" scoped>.red_rectangle {width: 500px; height: 300px; background-color: red; margin:0 auto; }.yellow_rectangle {width: 300px; height: 200px; background-color: yellow; margin:0 auto; padding: 50px; background-clip: content-box; text-align: center; }.blue_text {color: blue; line-height: 200px;}</style>
效果展示: