css - 将 DIV 定位到居中容器的两侧

标签 css positioning css-position

我的页面内容有一个水平居中的主容器 DIV:

HTML:

<div id="master_container">
  .. my content here ...
</div>

CSS:

#master_container {width: 960px; margin: 0 auto;}

客户希望在 master_container 之外的页面两侧都有广告。我尝试了各种 CSS 来尝试定位这些 div,但是当调整窗口大小时,它们与 master_container 重叠。另外,我被要求在页面滚动时让它们 float 。

任何人都可以指导我找到正确的解决方案吗?提前致谢...

最佳答案

>> DEMO <<

[请注意,我为 #master_container 使用了 700 像素的宽度]

1。定位

最重要的 CSS 是广告的样式和定位,我已经给 .advertis 类:

.advertis {
    position: fixed; /*creates floating effect */
    top: 20px; /* divs will always stay 20px from top */
    width: 220px;
    padding: 10px;
    background: white;
    border: #ccc 1px solid;
    border-radius: 4px;
}

#left {
    margin-left: -613px; left: 50%; /* positioning of left ads */
} 

#right {
    margin-right: -613px; right: 50%; /* positioning of right ads */
} 

我能听到您想知道:我如何计算我需要的 margin ?简单:

获取 #master_container 的宽度(包括填充)= 720px。将它除以 2 = 360px。添加广告的宽度(包括内边距和边框)= 242px240px + 360px = 600px。在容器和广告之间添加您想要的空间 = 11px(在我的例子中)。

242px(广告全宽)+ 360px(容器的一半)+ 11px(广告和容器之间的空间)= 613px(所需边距)

2。窗口太小时隐藏

现在您想要在广告不再适合窗口时隐藏它们。您可以选择:

  • 媒体查询
  • jQuery(或 JavaScript 或其他库)

在第一个 jsFiddle 中,我使用了媒体查询(并非所有浏览器都支持)。在 this Fiddle,我使用 jQuery 来获得相同的效果。

function widthCheck() {
    var ads = $(".advertis");

    if ($(window).width() < 1225) {
        ads.hide();
    }
    else {
        ads.show();
    }
}

widthCheck(); // Execute onLoad

$(window).resize(function(){
    widthCheck();  // Execute whenever a user resizes the window
});

您可以选择要使用哪一个。我将列出一些优缺点,以便您自己选择。

专业媒体查询:

  • 现代、进步
  • 即使在禁用 JS 时也能正常工作

缺点:

  • 并非所有浏览器都支持

jQuery 的优点:

  • 被(和)所有浏览器支持

缺点:

  • 禁用 JS 时不起作用
  • 不像媒体查询那样进步

关于css - 将 DIV 定位到居中容器的两侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11491060/

相关文章:

javascript - 单击并不总是触发切换事件

php - 如何根据时间在 td 中定位 div 看起来像谷歌日历

css - CSS : font: 0px/0px a; 中这是什么声明

html - 悬停时如何停止圆圈上的抖动

css - 媒体查询如何 react

html - 什么 css 位置 : or overflow do you use for smaller screens/minimized screens?

css - 在 div 的右边缘附近放置超链接

css - 使用CSS制作没有滚动条但页脚位于底部的页面

javascript - 带有下拉子菜单的 Css 响应式导航

html - 如何让页面在固定容器下滚动?