'Stretching' a div to the edge of a browse

2019-06-28 06:21发布

I'm trying to achieve a fixed width centred layout with headings that 'stretch' to the edge of the users browser. Like this...

Layout Example

Any ideas how I can achieve this?

5条回答
beautiful°
2楼-- · 2019-06-28 06:46

Maybe you could use an illusion to accomplish this? You can try having a blue bar with width = 100% sit behind all of your page content, such that it is only exposed to the right of the blue "sub-heading" section, but always reaches the right edge. You just have to make sure you eclipse the rest of it (anything to the left of the blue "sub-heading" element).

查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-28 07:03

Here is my attempt using JavaScript, maintaining a fixed width center: Demo

Otherwise, I don't think what you want is possible using pure CSS, but I could be mistaken.

查看更多
叼着烟拽天下
4楼-- · 2019-06-28 07:06

Perhaps this would work?

<h1 id="mainHeader">Heading</h1>

#mainHeader {
    float:left;
    clear:both;
    width:800px;
    background-color:#ff0000;
    color:#fff;
}
查看更多
地球回转人心会变
5楼-- · 2019-06-28 07:12

This works splendidly. It could use some refinements, but the idea is quite solid.

Live Demo (edit)

CSS:

html, body {
    margin: 0;
    padding: 0;
    border: 0;
    overflow-x: hidden
}
body {
    background: #eee
}
#container {
    width: 80%;
    margin: 0 auto;
    background: #bbb;
}
#menu {
    overflow: auto
}
#menu li {
    float: left;
    width: 40px;
    margin: 5px;
    height: 24px;
    background: #fff
}
h1, h1 span, h2, h2 span {
    padding: 3px 0;
    height: 25px;
}
h1, h2 {
    position: relative;
    margin: 9px 0
}
h1 span, h2.left span {
    display: block;
    position: absolute;
    width: 100%;
    left: -100%;
    top: 0
}
h2.right span {
    display: block;
    position: absolute;
    width: 102%;
    left: 100%;
    top: 0
}

h1 {
    background: red;
    width: 80%
}
h1 span {
    background: blue /* blue for demonstration purposes */
}
h2.left {
    background: red;
    width: 30%;
    float: left
}
h2.left span {
    background: blue /* blue for demonstration purposes */
}
h2.right {
    background: red;
    width: 30%;
    float: right
}
h2.right span {
    background: blue /* blue for demonstration purposes */
}

#content {
    clear: both
}

HTML:

<div id="container">
    <h1><span></span>Heading</h1>
    <h2 class="left"><span></span>Sub-heading</h2>
    <h2 class="right">Sub-heading<span></span></h2>
    <div id="content">
        Hi!
    </div>
</div>
查看更多
相关推荐>>
6楼-- · 2019-06-28 07:13

if you want be fixed in the window you can use position:fixed otherwise position:absolute. Then with left:0 and right:0 you position them in the left or right side. Using top you can set the offset from top.

Demo: http://jsbin.com/awoke3

查看更多
登录 后发表回答