CSS裁剪中心&规模

时间:2014-12-18 01:07:03

标签: html css

我想创建一个适用于任何显示尺寸的网站,为此,我需要一种方法来相应地裁剪,居中和缩放图像。

图像为2560x735,以下是对不同显示器的反应:

我目前的尝试是在这个代码段中:



div {
  width: 100%;
  height: 735px;
  min-width: 980px;
  background-image: url('http://cl.ly/Z0O0/01940_morainelake_2560x1440.jpg');
  background-position: center center;
}

<div></div>
&#13;
&#13;
&#13;

2560x735

2560X735

1920x735

1920x735

980x735 - 这是图像的最小宽度

980x735

375x735

这是与之前相同的图像(980x735),但缩放到显示宽度的100%。媒体查询可能在这里很有用。

375x735

2 个答案:

答案 0 :(得分:0)

如果您希望在特定维度调整大小,我会说您可能希望使用@media CSS at-rule(review it on Mozilla Dev Network)。除此之外,只需填写

body {
    background: url('http://yourimage.com');
}

指定您需要的任何其他适用属性,例如no-repeat等等

看看这个 http://www.smashingmagazine.com/2013/07/22/simple-responsive-images-with-css-background-images/

答案 1 :(得分:0)

要确保图像正确缩放,最简单的方法是使用background-size: cover属性。它会将您的背景图像缩放到容器内的最大尺寸。

就像我在评论中提到的那样,您必须为容器div设置一个高度 - auto无法正常工作,因为background-image没有向div添加任何内容,所以它的高度将为0否则。

这就是我要做的事情:

<强> CSS

html,body {        /* This ensures no white border around your page */
  margin:0;
  padding:0;
  height:100%;
  width:100%;
}
#container {
  width:100%;
  height:100%;
  background: url('your-image-url-here') center center no-repeat;
  background-size: cover;
}

这是一个 CodePen demo ,显示了一个简单的例子。

相关问题