0

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

HTML:

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

CSS:

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

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

谁能指导我找到正确的解决方案?提前致谢...

4

2 回答 2

1

那个怎么样:

演示:http: //jsfiddle.net/insertusernamehere/Ct5BM/

HTML

<div id="master_container">
    <div class="ad left">Advertising</div>
    <div class="ad right">Advertising</div>
    The real content …
</div>

CSS

<style>

    body {
        width:      100%;

    }

    #master_container {
        position:   relative;
        width:      960px;
        height:     500px;
        margin:     0 auto;
        border:     1px solid red;
    }

    div.ad {
        position:   absolute;
        top:        0px;
        width:      200px;
        height:     400px;
        margin:     0px 0px 0px 0px;
        border:     1px solid blue;
    }

    div.ad.left {
        left:       -220px;
    }

    div.ad.right {
        right:      -220px;
    }

</style>

编辑:它是如何工作的

当您相对定位主元素时,它不会从其内容中的流中取出,但会为定位、z-indexes 等打开一个新空间。因此,此容器中具有绝对位置的子元素与其位置相关父母。所以在这个例子中,“ad”元素的宽度为 200px,左边为 -220px,它被移动到左侧容器的外部,并添加了一点“边距”。

于 2012-07-15T10:19:42.373 回答
1

>>演示<<

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

一、定位

最重要的 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 */
} 

我可以听到你想知道:我如何计算我需要的保证金?简单的:

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

242px (full width of ad) + 360px (half of container) + 11px (space between ad and container) = 613px (margin needed)

2.窗口太小隐藏

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

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

在第一个 jsFiddle 中,我使用了媒体查询(并非所有浏览器都支持)。在这个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
});

​</p>

您可以选择要使用哪一个。我会列出一些优点和缺点,所以你可以自己选择。

专业媒体查询:

  • 现代的,进步的
  • 工作,即使 JS 被禁用

缺点:

  • 并非所有浏览器都支持

优点 jQuery:

  • 所有浏览器都支持(和)一样好

缺点:

  • 禁用 JS 时不起作用
  • 不像媒体查询那样进步
于 2012-07-15T10:49:42.990 回答