CSS layout (2 column layout, but if no sidebar main column must be 100% wide)

时光怂恿深爱的人放手 提交于 2019-12-11 14:56:06

问题


Column1 (left) is for content. Column2 (right/ sidebar) is for related info. say layout is 66%/34%. I need a way to make Column1 to stretch to 100% automatically if there is no sidebar content. Any idea's. I know it can be done. I just can't remember how.

+---------+---------+
| Content | sidebar |
+---------+---------+


+-------------------+
|Content/ no-sidebar|
+-------------------+

回答1:


You might try something like this. Here are the two different HTML cases:

With sidebar:

<div id="container">
    <div id="sidebar">some content</div>
    <div id="main_content">main content</div>
</div>

Without sidebar:

<div id="container">
    <div id="main_content">main content</div>
</div>

And here is the CSS the conditionally changes the sizing of the main_content div:

#container {
    overflow: hidden;
}

#sidebar {
    width: 34%;
    float: right;
}

#main_content {
    width: 100%;
    float: left;
}
#main_content:nth-child(2) {
    width: 66%;
}



回答2:


You may set HTML like;

<div id="container">
    <div id="content">content
        <div id="sidebar">sidebar</div>
    </div>
</div>

and CSS like;

#container{
    width: 100%;
}
#sidebar, #content{
    height: 200px;

}
#sidebar{
    width: 200px;
    float: left;
}
#content{
    background: orange;
}

you may replace px with percentage. Here is a Live Demo.



来源:https://stackoverflow.com/questions/12302935/css-layout-2-column-layout-but-if-no-sidebar-main-column-must-be-100-wide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!