Html 无论浏览器大小如何,始终保持图像居中
我想知道是否可以在Html 无论浏览器大小如何,始终保持图像居中,html,css,Html,Css,我想知道是否可以在div中始终保持img居中,而不考虑浏览器大小?居中是指图像的左/右侧被裁剪,以确保图像保持居中而不修改高度。此外,当浏览器宽度小于图像宽度时,是否可以防止出现水平滚动条 我确信,如果我的图像位于CSS中的背景url标记中,那么这确实很容易做到,但由于此图像位于SlidesJS旋转木马中,因此图像必须来自img标记 目前,我使用了margin:0auto只要浏览器宽度大于图像,就可以使图像居中。浏览器宽度缩小后,图像不会随着浏览器大小的缩小而调整大小。我还没有弄清楚当浏览器宽度
div
中始终保持img
居中,而不考虑浏览器大小?居中是指图像的左/右侧被裁剪,以确保图像保持居中而不修改高度。此外,当浏览器宽度小于图像宽度时,是否可以防止出现水平滚动条
我确信,如果我的图像位于CSS中的背景url
标记中,那么这确实很容易做到,但由于此图像位于SlidesJS旋转木马中,因此图像必须来自img
标记
目前,我使用了margin:0auto
只要浏览器宽度大于图像,就可以使图像居中。浏览器宽度缩小后,图像不会随着浏览器大小的缩小而调整大小。我还没有弄清楚当浏览器宽度太小时如何删除水平滚动条
这就是我想要实现的目标:
这是一个页面布局的示例:
我的代码示例:
HTML:
对于滚动条,我不确定对齐中心是否适合我。 您可以使用以下选项:
overflow-x: hidden;
试试这个:
要裁剪边,可以执行以下操作:
Jeff Hines链接了ShankarSangoli解释如何实现这一点的地方
img.centered {
position:fixed;
left: 50%;
top: 50%;
/*
if, for instance, the image is 64x64 pixels,
then "move" it half its width/height to the
top/left by using negative margins
*/
margin-left: -32px;
margin-top: -32px;
}
看看这个:@JeffHines很棒。非常感谢。这正是我所需要的。看起来很棒,但我不想修改图像的高度。我只想根据需要裁剪边缘,以保持图像居中。为了好玩,我制定了您想要的布局:我觉得上面提到的带有循环图像的JSFIDLE并不能保持所有图像居中,如果它们具有不同的图像宽度。似乎不起作用。您在哪里应用了
overflow-x:hidden
to?您可以将其应用于body或包含滚动条的div。这可能是浏览器问题。请尝试以下操作:body{overflow:-moz scrollbars vertical;overflow-x:hidden;overflow-y:scroll;}\uuuuu将overflow-x
应用于body似乎已经达到了效果,但我只需要将其应用于图像。当我这么做的时候,它仍然不起作用。不管怎样,@Jeff Hines已经链接了一个解决方案。谢谢你的帮助:)
overflow-x: hidden;
#wrapper {
max-width: 200px; /* max-width doesn't behave correctly in legacy IE */
margin: 0 auto;
}
#wrapper img{
width:100%; /* the image will now scale down as its parent gets smaller */
}
#wrapper {
max-width: 600px; /* so this will scale down when the screen resizes */
margin: 0 auto;
overflow:hidden; /* so that the children are cropped */
border:solid 1px #000; /* you can remove this, I'm only using it to demonstrate the bounding box */
}
#wrapper .slides_container{
width:600px; /* static width here */
position:relative; /* so we can position it relative to its parent */
left:50%; /* centering the box */
margin-left:-300px; /* centering the box */
}
#wrapper img{
display:block; /* this allows us to use the centering margin trick */
margin: 2px auto; /* the top/bottom margin isn't necessary here, but the left/right is */
}
img.centered {
position:fixed;
left: 50%;
top: 50%;
/*
if, for instance, the image is 64x64 pixels,
then "move" it half its width/height to the
top/left by using negative margins
*/
margin-left: -32px;
margin-top: -32px;
}