html - 无论页面大小如何,将标题图像居中

标签 html css image center crop

我的网页有一个始终位于窗口顶部的标题图像。当窗口最大化时,标题图像居中,但在小窗口(或智能手机浏览器)中查看时,标题设置在窗口左侧,右侧被裁剪。因为标题 div 比页面内容宽,当窗口小于标题而不是页面时,水平滚动条出现。

我希望页眉图像始终位于页面中央,如果窗口小于页眉,则左右两边都被裁剪。此外,水平滚动条仅在窗口宽度小于页面宽度时才会打开。

这张图片可能会更清楚地解释它:

image http://postimage.org/image/49ne3k3o/

到目前为止我的代码:

CSS:

#headerwrap {
    position: relative;
    width: 998px;
    height: 100px;
    margin: 0 auto;
    pointer-events: none;
}
#header{
    position: fixed;
    top: 0;
    width: 998px;
    margin: 0;
    background: url('../images/top.png') no-repeat;
    height:100px;
    z-index: 1;
    pointer-events: none;
}

和 HTML 实现:

<div id="headerwrap"\>
<div id="header">
</div>
</div>

(页面宽690px,页眉998px)

如有任何帮助,我们将不胜感激。

最佳答案

您需要在具有 position: fixed 的标题元素上设置 left: 50%,然后应用该元素宽度一半的负边距以使其居中。

#header {
  height: 100px;
  width: 998px;
  position: fixed;
  top: 0;
  left: 50%;
  margin-left: -499px;
  background: url('../images/top.png') no-repeat;
}

这是一个快速的 fiddle :http://jsfiddle.net/blineberry/w8P2S/

你真的不需要包装器。

关于html - 无论页面大小如何,将标题图像居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6475399/

相关文章:

javascript - 动态加载 SVG 时,SVG 填充 ="url(#foo)"消失

jquery - 提高 jQuery 拖动动画的性能

c++ - 图像稳定

html - 如何使不同字体大小的按钮高度相同

c# - 如何从外部位置提取 HTML block 并使用 Razor 呈现它?

javascript - Ionic 2从ts文件引用html文件中的值?

machine-learning - 如何将张量写入 PNG 图像文件?

javascript - 为什么点击或更改事件都没有触发我的功能?

javascript - 从百分比设置特定梯度

jquery - 图像上的 CSS 过渡不起作用