html – 无论浏览器大小如何,始终将图像保持为中心

前端之家收集整理的这篇文章主要介绍了html – 无论浏览器大小如何,始终将图像保持为中心前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道是否有可能在一个div内部保持一个img始终居中,无论浏览器大小如何?通过居中我的意思是图像的左/右侧被裁剪以确保图像保持居中而不修改高度.此外,当浏览器宽度小于图像宽度时,是否可以防止出现水平滚动条?

我确信如果我的图像位于CSS中的background-url标记中,这很容易做到,但由于此图像位于SlidesJS轮播内,因此图像必须来自img标记.

目前,我使用了margin:0 auto;只要浏览器宽度大于图像,就保持图像居中.一旦浏览器宽度缩小,图像就不会随着缩小的浏览器大小而调整大小.我还没有弄清楚当浏览器宽度太小时如何删除水平滚动条.

这就是我想要实现的目标:http://imgur.com/Nxh5n

这是页面布局的示例:http://imgur.com/r9tYx

我的代码示例:http://jsfiddle.net/9tRZG/

HTML:

  1. <div id="wrapper">
  2. <div id="slides">
  3. <div class="slides_container">
  4. <div class="slide"> <!-- Carousel slide #1 -->
  5. <img src="http://www.placehold.it/200x50/">
  6. </div>
  7. <div class="slide"> <!-- Carousel slide #1 -->
  8. <img src="http://www.placehold.it/200x50/">
  9. </div>
  10. <div class="slide"> <!-- Carousel slide #1 -->
  11. <img src="http://www.placehold.it/200x50/">
  12. </div>
  13. </div>
  14. </div>
  15. </div>

CSS:

  1. #wrapper {
  2. width: 200px;
  3. margin: 0 auto;
  4. }​

解决方法

试试这个: http://jsfiddle.net/9tRZG/1/
  1. #wrapper {
  2. max-width: 200px; /* max-width doesn't behave correctly in legacy IE */
  3. margin: 0 auto;
  4. }
  5. #wrapper img{
  6. width:100%; /* the image will now scale down as its parent gets smaller */
  7. }

要裁剪边缘,可以执行以下操作:http://jsfiddle.net/9tRZG/2/

  1. #wrapper {
  2. max-width: 600px; /* so this will scale down when the screen resizes */
  3. margin: 0 auto;
  4. overflow:hidden; /* so that the children are cropped */
  5. border:solid 1px #000; /* you can remove this,I'm only using it to demonstrate the bounding Box */
  6. }
  7.  
  8. #wrapper .slides_container{
  9. width:600px; /* static width here */
  10. position:relative; /* so we can position it relative to its parent */
  11. left:50%; /* centering the Box */
  12. margin-left:-300px; /* centering the Box */
  13. }
  14. #wrapper img{
  15. display:block; /* this allows us to use the centering margin trick */
  16. margin: 2px auto; /* the top/bottom margin isn't necessary here,but the left/right is */
  17. }

猜你在找的HTML相关文章