首页 > 解决方案 > How to get an image to appear in a header, fully sized when the screen is wide enough but centered when the screen is too thin?

问题描述

I have an image I am using in the header of a website, and on a computer the image takes up the whole width as intended. When the site is displayed on mobile devices however, it scales down and only shows the far left side of the image.

.backimage {
padding:20px;
background-image:url(background.jpeg);
width:100%;
height:35%;
background-repeat:no-repeat;
background-size:cover;
}

Is there some code I can add to center the image when the width is too small for the whole image? Thanks, if more information is needed I will provide.

标签: htmlcss

解决方案


使用@mediaquery

  @media only screen and (max-width: 600px) {
    .backimage {
       padding:20px;
       background-image:url(background.jpeg);
       width:50%;
       height:35%;
       margin-left: 0px;
       background-repeat:no-repeat;
       background-size:cover;
    }
  }

如果浏览器窗口为 600 像素或更小,则图像宽度将为 50%。

如果您想要不同尺寸的不同样式,您可以使用

  @media only screen and (max-width: 900px) {
    .backimage {
       padding:20px;
       background-image:url(background.jpeg);
       width:70%;
       height:35%;
       margin-left: 0px;
       background-repeat:no-repeat;
       background-size:cover;
    }
  }

如果浏览器窗口为 900 像素或更小,则图像宽度将为 70%。


推荐阅读