平时在使用css进行网页布局时,由于每台电脑的屏幕分辨率不一样,所以我们会将最大的图片宽度设置为1920px,但是在分辨率小于1920px情况下,浏览网页,该图片会出现偏移,如果我们想让该图片居中显示,方法其实也很简单,需要给img加一个属性:margin: 0 -100%;
通过网络搜集,找到两种方法,并且验证后都可使用,具体如下
第一种:使用定位流让图片居中:这种方法有明显的弊端,需要知道图片的宽度
<head>
<meta charset="UTF-8">
<title>图片居中方式</title>
<style>
.father{
width: 100px;
height: 100px;
margin: 0 auto;
border: 5px solid red;
box-sizing: border-box;
text-align: center;
}
.hubuw{
position: absolute;
left: 50%;
/*宽度为图片宽度的一半*/
margin-left: -206px;
}
</style>
</head>
<body>
<div class="father">
<img src="tab.jpg" class="hubuw">
</div>
</body>
第二种:使用margin: 0 -100%;这种方法父元素必须text-align: center;
<head>
<meta charset="UTF-8">
<title>图片居中方式</title>
<style>
.father{
width: 200px;
height: 100px;
margin: 0 auto;
border: 5px solid red;
box-sizing: border-box;
text-align: center;
}
.hubuw{
margin: 0 -100%;
}
</style>
</head>
<body>
<div class="father">
<img src="tab.jpg" class="hubuw">
</div>
</body>