html标签中的内容居中html不用class怎么居中

第一种:将元素通过display:inline-block转化为行内块元素居中,例如:

.box{ width:500px; height:500px; box-shadow:0 0 5px #000; text-align:center; font-size:0; }

.box .zi{ width:120px; height:100px; background:#0f0; display:inline-block; vertical-align:middle; }

.box:after{ content:””; display:inline-block; height:100%; vertical-align:middle; }

第二种:用定位的方式将之移动到位置,例如:

.box{ width:500px; height:500px; box-shadow:0 0 5px #000; position:relative; }

.box .zi{ width:120px; height:100px; background:#0f0;

position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; }

第三种:类似第二中只不过通过百分比调整位置,例如

.box{ width:500px; height:500px; box-shadow:0 0 5px #000; position:relative; }

.box .zi{ width:120px; height:100px; background:#0f0; position:absolute; left:50%; top:50%; margin:-50px 0 0 -60px; }

第四种:类似第三种,但是在调整回到中心位置时使用transform:translate( ,)进行调整,例如

.box{ width:500px; height:500px; box-shadow:0 0 5px #000; position:relative; }

.box .zi{ width:120px; height:100px; background:#0f0;

position:absolute; left:50%; top:50%; transform:translate(-50%,-50%); }

第五种:使用弹性盒(display:flex),例如

.box{ width:500px; height:500px; box-shadow:0 0 5px #000; display:flex; justify-content:center; align-items:center; }

.box .zi{ width:120px; height:100px; background:#0f0; }

以上最常用的五种方式,除此之外还有很多方式,根据每个人的习惯不同个人用法不同,

首先我们需要新建一个html页面。

然后在body部分新建一个img标签,并指定一张图片。

在浏览器中查看效果,可以发现图片是默认左对齐的,并没有在正中央显示。

将图片套在一个p或者span标签中,给标签添加一个值为text-align:center的style属性即可。

#warning{ width: 987px; margin: 0 auto; height:80px; line-height:80px; background:#ffd; position:fixed; _position:absolute; top:0; z-index:99999; overflow:hidden; } 要居中的话宽度不能用百分比 只能是具体数值