javascript - 如果页面大于 div,则仅居中 div

标签 javascript html css

所以我在这里使用这种样式将 div 作为背景居中:

#example{
    z-index:-1; 
    width: 950px; 
    height:100%; 
    position:fixed; 
    background-color:#F0F0F0;
    background:url(images/main_background_sidebar.png) repeat-y top center;
    top: 0px;
    left: 50%;
    margin-left: -475px;
}

效果很好,它保持居中,但如果页面宽度小于 950 像素,是否有办法阻止它保持居中?例如:如果浏览器窗口只有 800px 宽,则背景图像的左侧会粘在屏幕的左侧。

最佳答案

如果您可以使用 CSS3,那么您可以申请 @media规则。一个未经测试的可能性:

#example {
   /* Don't center it. */
}
@media only screen and (min-width: 950px) and (min-device-width: 950px)  {
  #example {
   /* It's 950px or more! Let's center it! */
  }
}

只需阅读并使用它即可。

更新:我该如何使用它?我应该把它放在哪里,就在我的 style.css 中?

Media queries can be used in tags, XML processing instructions, the @import at-rule, and the @media at-rule.

关于javascript - 如果页面大于 div,则仅居中 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066526/

相关文章:

javascript - 如何从最后一次看到的字符串中获取JavaScript中特定字符的子字符串?

javascript - 用数组绘制D3简单折线图

javascript - 踩范围输入

html - 为什么在 Chrome 51 中查看的 SVG 无法正确定位并在文本后添加间隙?

ruby-on-rails - 下拉导航菜单

css - 如何在页面中心对齐div?

javascript - 如何使用数据数组来制作选定的复选框?

php - 如果禁用了 javascript 并且您想要在 PHP 或正则表达式中准确地 (XXX)XXX-XXXX,如何过滤(和替换)phone# 输入

html - 双下拉 - 带 OVERFLOW 第 3 列子列表

javascript - Tipsy Tooltip 箭头问题