0


Vue组件居中:文字居中,按钮居中,图片居中等,如何实现在容器中居中

Vue实现组件在容器中居中显示的办法

本文用实验的方法理解各种方法实现居中的效果。
实现水平居中的样式主要有:text-align: center, margin: auto。
当然还有别的方式也可以实现,也会写在下面。
用三个同样的div来控制变量法看效果,这三个div既是组件也是容器。下面将他们分别叫做A,B,C。

<template><div><!--A--><divstyle="border:solid #409eff ;width: 400px;height: 200px;"><el-button>1</el-button><divstyle="border:solid bisque;width: 200px;height: 100px;"><el-button>2</el-button><divstyle="border:solid chartreuse;width: 100px;height: 50px;"><el-button>3</el-button></div></div></div><!--B--><divstyle="border:solid #409eff ;width: 400px;height: 200px;"><el-button>1</el-button><divstyle="border:solid bisque;width: 200px;height: 100px;"><el-button>2</el-button><divstyle="border:solid chartreuse;width: 100px;height: 50px;"><el-button>3</el-button></div></div></div><!--C--><divstyle="border:solid #409eff ;width: 400px;height: 200px;"><el-button>1</el-button><divstyle="border:solid bisque;width: 200px;height: 100px;"><el-button>2</el-button><divstyle="border:solid chartreuse;width: 100px;height: 50px;"><el-button>3</el-button></div></div></div></div></template>

border//边框的显示及颜色
width//宽度
height//高度
最初效果

text-align: center效果

将text-align: center放到div的style中;
分别应用于A的大框,B的中框,C的小框中。

代码只取A展示,其它的不再赘述,后面也不再重复展示代码

<divstyle="border:solid #409eff ;width: 400px;height: 200px;text-align: center;"><el-button>1</el-button><divstyle="border:solid bisque;width: 200px;height: 100px;"><el-button>2</el-button><divstyle="border:solid chartreuse;width: 100px;height: 50px;"><el-button>3</el-button></div></div></div>

改动后效果如下:
text-align应用于各个div中产生的效果
红色箭头是被应用的div框。
可以看出,text-align: center可以使该容器内部元素在该容器内水平居中,但不能使子容器在该容器内部水平居中。子容器继承了父容器,故在最大容器中应用了text-align: center后,其子容器也有此效果。

margin: auto效果

清除掉text-align: center 用margin: auto来替代,还是分别应用于A的大框,B的中框,C的小框中。
效果如下:
margin: auto
红色箭头是被应用的div框。
可以看出,应用了margin: auto的div组件,在它所处的容器中水平居中,并且这是作为组件的属性,而不是作为容器的属性,故不会传给子容器。

用两个空组件来让组件水平居中效果

只取A做如下改动

<template><div><divstyle="border:solid #409eff ;width: 400px;height: 200px;"><el-button>1</el-button><divstyle="border:solid bisque;width: 200px;height: 100px;"><divstyle="display: flex"><divstyle="flex: 1"></div><el-button>2</el-button><divstyle="flex: 1"></div></div><divstyle="display: flex"><divstyle="flex: 1"></div><divstyle="border:solid chartreuse;width: 100px;height: 50px;"><el-button>3</el-button></div><divstyle="flex: 1"></div></div></div></div></div></template>

效果如下:
两个空组件
在这里插入图片描述
这种方法是用一个容器套住你想要水平居中的内容,再在这个内容的左右各放一个等大的组件(容器),就可以实现水平居中了。

<el-button>想要居中的内容</el-button>

将上面换成下面。

<divstyle="display: flex"><divstyle="flex: 1"></div><el-button>想要居中的内容</el-button><divstyle="flex: 1"></div></div>
标签: vue.js html5 css

本文转载自: https://blog.csdn.net/yuanqianxi/article/details/123752634
版权归原作者 Drawing stars 所有, 如有侵权,请联系我们删除。

“Vue组件居中:文字居中,按钮居中,图片居中等,如何实现在容器中居中”的评论:

还没有评论