首页 > 面试问题,怎样让图片100%居中在屏幕中间呢

面试问题,怎样让图片100%居中在屏幕中间呢

面试问题,怎样让图片100%居中在屏幕中间呢


这个有好几种方法啊。
一、用margin负值,这种方法适合宽高固定。
position:absolute;
left:50%;
top:50%;
margin-left:-宽度的一半;
margin-top:-高度的一半;

二、使用css3新属性translate,这个不需要固定宽高。
position:absolute;
left:50%;
top:50%;
transform:translate(50% 50%);

三、使用flex布局,这个也不需要固定宽高。
在父容器上面设置
display:flex;
justify-content:center;
align-items:center;
这样也可以实现居中。

四:将上下左右全设为0.
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
这样全部设为0后会拉伸图片充满父容器,然后margin设为auto会自动填充上外边距,就能实现居中。


左边距 = (图片宽度 + 屏幕宽度)/2;
上边距 = (图片高度 + 屏幕高度)/2;


background : url('');
left:0;
right:0;
top:0;
bottom:0;
background-size:cover;
background-position:center;
position:absolute;

这样很适合解决背景图片自适应的问题。。


使用translate大法,好用又好记。只是对旧的浏览器不友好。

position:absolute;
left:50%;
top:50%;
transform:translateX(-50%) translateY(-50%);

position:absolute;
top:50%;
left:50%;
margin-top:-图片高度/2;
margin-left:-图片高度/2;
???


display: flex;
justify-content: center;
align-items: center;

lz是在长沙吗
应该是要求css去解决吧


position absolute top0 bottom0 left0 right0 margin auto

【热门文章】
【热门文章】