带有可选侧边栏的流体内容 div
我有一个问题,在我看过的各种 CSS 布局模型中都没有找到解决,所以我想我应该把它发布在这里。
我正在开发一个使用基本流体/固定两列布局的网站。网站的内容位于左侧 div,侧边栏位于右侧。侧边栏的固定宽度约为 200 像素左右,内容会扩展以填充父级的剩余宽度。
代码如下:
<div style="width: 90%; margin: 10px auto 10px auto;"> <!-- site container -->
<div style="margin-right: 200px;">Content goes here.</div>
<div style="float: right; width: 200px;">Menus goes here.</div>
<div style="clear: both;"></div> <!-- float-clearer div -->
</div>
这是一种非常标准的方法,在大多数情况下都可以正常工作,但问题是网站的设计要求侧边栏仅在某些情况下出现。所有的HTML都是通过PHP生成的,“get-content()”函数不知道“get-sidebar()”函数是否会被调用。
当调用侧边栏时,我希望内容展开以填充父 div,同时为侧边栏留出足够的空间。如果没有侧边栏,内容应展开以填充父级的整个宽度。
有没有办法用 CSS 来做到这一点——也许使用“auto”作为内容边距——而不依赖 PHP/JavaScript?
I have a question that I haven't found addressed in the various CSS layout models I've looked at, so I thought I'd post it here.
I'm working on a site that uses a basic fluid/fixed two-column layout. The content of the site is in the left div, and the sidebar in the right. The sidebar has a fixed width of 200 pixels or so, and the content expands to fill out the remaining width of the parent.
Here's what the code looks like:
<div style="width: 90%; margin: 10px auto 10px auto;"> <!-- site container -->
<div style="margin-right: 200px;">Content goes here.</div>
<div style="float: right; width: 200px;">Menus goes here.</div>
<div style="clear: both;"></div> <!-- float-clearer div -->
</div>
This is a pretty standard approach and works fine for the most part, but the issue is that the design of the site requires the sidebar to only appear in certain cases. All of the HTML is generated through PHP, and the "get-content()" function doesn't know whether the "get-sidebar()" one will be called or not.
When the sidebar is called, I'd like the content to expand out to fill the parent div while leaving enough room for the sidebar. If there is no sidebar, the content should expand out to fill the entire width of the parent.
Is there any way to do this with CSS -- perhaps using "auto" for the content margins -- without relying on PHP/JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能会考虑这样做:
通过这样做,菜单位于主 div 内,并且没有右边距,因此当菜单消失时,文本会扩展以填充空间。
“高度:100%;”确保菜单和内容框拉伸到相同的高度。如果需要,您还可以将其设置为像素或 em 数量或小于 100 的百分比。
You might consider doing it like this:
By doing it that way, the menu sits inside the main div and there is no margin-right, so when the menu goes away, the text expands to fill the space.
The "height:100%;" ensures that the menu and content boxes stretch to the same height. You could also set this to a pixel or em amount or a percentage less than 100 if you want.
不要浮动侧边栏,请尝试以下操作:
Instead of floating the sidebar, try this:
是否可以使用 PHP 将类添加到主体中?类似于“一列”或“二列”,具体取决于上下文。然后,当有侧边栏时,您可以给内容 div 留出边距,但在没有侧边栏时则不能。
Would it be possible to add a class to the body using PHP? Something like "one-col" or "two-col" depending on the context. Then you can give the content div a margin when there is a sidebar, but not when there isn't.