在HTML中使用元素居中需要什么注意事项-创新互联
这篇文章将为大家详细讲解有关在HTML中使用元素居中需要什么注意事项,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
不使用定位
水平居中:text-align = center;(可继承)
竖直居中:margin:0 auto;(块级元素)
其他居中:1.文字居中:父元素设置高 子元素设置高 line-height=height(父元素)
2.图片居中: vertical-aign:middle ; <-- 必须放在图片元素中
.first{ width: 300px; height: 100px; background-color: black; color: white; text-align: center; margin: 0 auto; //针对块级元素 }
不使用定位(1)
.second{ width: 300px; height: 100px; background-color: green; } .s_child{ width: 150px; line-height: 100px; }不使用定位(2)
2.定位居中
a.父元素高度固定
父元素:相对定位
子元素:绝对定位
top:50%(父元素高度的一半)
left:50%
margin-top:自己的高度一半;(加负号)
margin-left:自己宽度的一半;(加负号)
.dw_one{ width: 600px; height: 300px; position: absolute; background: black; } .dw_one_child{ background: white; position: relative; width: 50px; height: 50px; top: 50%; left: 50%; margin-top: -25px; margin-left: -25px; }a