问题
当我们有如下的布局时,其中 img 是我们内容,用一个 overflow:auto 来设置一个滚动区域,当图片较长时,会发现即使滚动到顶部,图片顶部仍有部分看不到。
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
.container {
width: 500px;
height: 500px;
overflow: auto;
display: flex;
justify-content: center;
align-items: center;
}
img {
width: 100%;
}
</style>
<body>
<div class="container">
<img src="./static/1.jpg" alt="" />
</div>
</body>
</html>
解决方法
设置内容的 margin:auto 就可以滚动显示完全了。
img {
width: 100%;
margin: auto;
}
我们换一张宽度较宽的图,并设置 height:100%,这时新的问题出现了,图片滚动到最左边,图片左边仍有部分被遮挡显示不全。
img {
height: 100%;
margin: auto;
}
继续解决
我们换一种居中布局的方式,就可是使图片左右滚动能显示全。
.container {
width: 500px;
height: 500px;
overflow: auto;
position: relative;
}
img {
height: 100%;
margin: auto;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
但是当我们换回高度较高的图片,并设置 width:100%时,发现问题又回来了,图片顶部显示不全。
难道说说没有一种同时能满足上下滚动和左右滚动显示全的布局方式吗?
解决方案
一般来说图片要么 width:100%,要么 height:100%,所以上面选一种布局方式即可,但是我写的一个页面刚好要在两种状态中进行切换,因为切换是通过 js 操作的,可以在 css 里写两个布局,然后通过 js 控制元素 class 来进行切换。
我在 flex 布局的基础上,当图片左右滚动不能显示完全时,只需要改变 flex-direction 的方向即可。
.container {
width: 500px;
height: 500px;
overflow: auto;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
img {
height: 100%;
margin: auto;
}