【问题标题】:Background image center and resize背景图像居中和调整大小
【发布时间】:2014-02-01 08:43:06
【问题描述】:

我正在为客户开发一个网站,其中有一个背景图片,该图片将位于页面中心,并覆盖有文本、链接等。

我目前已将图像大小调整如下:

img.bg
   {
   height:100%;
   position:absolute;
   }

这使图像适合浏览器的高度,但将其对齐到左侧。我需要它居中。

因为我需要它有条件地响应浏览器高度的变化,所以通常的居中技巧不起作用。

谢谢!

【问题讨论】:

    标签: html layout css


    【解决方案1】:

    尝试删除“位置:绝对”并添加边距:0 自动。例如:

    img.bg
    {
       height:100%;
       margin: 0 auto;
    }
    

    【讨论】:

    • 当我这样做时,图像只是将自身调整回原来的巨大尺寸。
    【解决方案2】:

    或者可能只是将其放在表格中<table align="center"> <tr><td>"image goes here"</td></tr> 它更易于管理,因为您将来可以毫无困难地向网页添加更多项目,添加边框,更改表格颜色等。

    【讨论】:

      【解决方案3】:

      我可以想到几种方法(未经测试,因此您可能需要调整):

      img.bg {
         position: absolute;
         /* Top and/or bottom for stretching it vertically as needed. Setting both will likely make it the size of the whole body, so beware. Remove bottom to keep it from doing that if necessary. */
         top: 0;
         bottom: 0;
         /* Left and/or right for sizing/positioning */
         left: 25%; /* Percentage position will make it adjust to browser window size, exact percent may need to be tweaked to get right and will depend on the image's size. */
      }
      
      
      img.bg {
         display: block;
         height: 100%;
         width: 500px; /* Whatever your desired width is. */
         margin: 0 auto; /* This should work as long as width is set. */
      }
      

      根据您的具体设计,其中任何一个都应该可以工作并且可以响应浏览器窗口的大小。第二个可能是最灵活且最容易实现的,因为您不必摆弄定位。

      【讨论】:

        【解决方案4】:

        答案取决于你所追求的。

        如果您希望在网站背景中显示图像(我想您是在说),那么我不确定您使用的是什么方法,但如果您在 html 和 css 中取消 img.bg{},只需将以下内容放入您的 CSS 中,您就会得到您想要的...

        body{
            background-image:url('background.gif'); // substitute background.gif for the correct file path
            background-repeat:no-repeat;
            background-attachment:fixed;
            background-position:center;
            background-size:auto 100%;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-10
          • 2018-01-01
          • 2012-04-10
          • 2017-01-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多