9

I know that position: fixed makes an element relative to the viewport instead of it's offsetParent however I have an issue where I have a side element which takes x amount of space and then some fixed position heading elements which I want to take up a percentage of the remaining viewport width.

See fiddle: http://jsfiddle.net/U5DSZ/

Now I could put all the h1 element's into their own container but then they lose their semantic meaning as they are no longer associated with their content.

I understand JavaScript could do this but I am against using JavaScript for page structure.

Is there a way to do this in a purely HTML or CSS way? I don't mind moving the h1 element's as long as they retain their relationship with the content and the content remains statically positioned.

4

2 回答 2

7

你可以得到你想要的效果如下。

您的 HTML 代码段很好:

<div id="content">
    <section>
        <h1>Heading 1</h1>
        <p>...</p>
    </section>
    <section>
        <h1>Heading 2</h1>
        <p>...</p>
    </section>
</div>

CSS很好,但只需要一些解释:

#content {
    overflow: visible; /* default, but important to notice */
}

section {
    float: left;
    width: 25%;
}

h1 {
    position: fixed;
    width: 25%;
    background: #00FF00;
    text-align: center;
}

和演示小提琴:http: //jsfiddle.net/audetwebdesign/4zLMq/

这是如何工作的

您的#content块占据了 200px 左侧浮动边栏右侧的剩余宽度。

#content中,您有两个左浮动section元素,它们占据了父容器的 25%,在本例中,它是视口面板的宽度。

您的子h1元素有position: fixed,这意味着它们的 25% 宽度也是根据视口的宽度(不是#content)计算的。

情况 1
如果您想要h1#content 具有相同的宽度,它们需要具有从相同的包含块(在本例中为视口)计算的相同相对值(25%)。

但是,25% 的值并不是考虑浮动侧边栏后剩余空间的 25%。但是,也许您可​​以忍受这一点。

案例 2
如果您将侧边栏宽度设置为相对值,您可以使宽度值更容易确定。使用混合单位总是一个问题。

于 2013-06-03T16:07:05.943 回答
0

tldr; 更短更清洁的解决方案:

h1 {
    width: inherit;
    ...

我偶然发现了这个问题,有一个类似的问题:我的容器的大小可以通过 resize:both 用户定义(也可以移动!)。

如果我遵循公认的解决方案,这意味着我必须将相同的道具应用于容器内的固定标题(顶部、左侧、宽度和高度……)。

相反,从父容器继承宽度可以正常工作。我发现这种方式更简单,也更有意义,在主要浏览器和手机上进行了测试(演示)。

于 2017-07-24T09:52:46.703 回答