如何覆盖现有的CSS让子<div> 1具有固定宽度,而子<div>具有父级的剩余宽度?</div> </div>

时间:2012-06-25 10:42:53

标签: css

我正在尝试为StackExchange网站编写Firefox时尚css(全屏宽度样式)。

在标记的问题列表页面(例如:https://stackoverflow.com/questions/tagged/java)中,HTML如下所示

<div class='question-summary'>
    <div class='statscontainer'>
        <div>n votes</div>
        <div>n answers</div>
        <div>n views</div>
    </div>
    <div class='summary'>
        <h3>Question title</h3>
        <div>question excerpt ...</div>
        <div>tag1 tag2 tagN </div>
    </div>
</div>

原始CSS在父/子1 /子2上使用固定宽度

<style>
    .question-summary
    {
        float: left;
        width: 730px;
        background-color: silver;
    }
    .statscontainer
    {
        float: left;
        width: 86px;
        margin-right: 8px;
        background-color: gray;
    }
    .summary
    {
        float: left;
        width: 635px;
        background-color: lightgray;
    }
</style>

现在我尝试覆盖CSS以使其适合全屏宽度

    .question-summary
    {
        float: left;
        width: 100% !important;    /* parent: full screen width */
        background-color: silver;
    }
    .statscontainer
    {
        float: left;
        width: 86px;    /* child 1: fixed width */
        margin-right: 8px;
        background-color: gray;
    }
    .summary
    {
        float: left;
        /*
        width: 80% !important;   <--- how to let child 2 has remaining width ?
        left: 95px;
        right: 0px;
        */
        background-color: lightgray;
    }

问题是,如何让孩子2保持宽度?我知道在使用<table>来控制布局时,这很容易。

<table style='width:100%'>
    <tr>
        <td bgcolor='gray' style='width:80px'>fixed width</td>
        <td bgcolor='lightgray'>automatically has remaining width</td>
    <tr>
</table>

修改

根据@sandeep和@MrLister的答案,它应该覆盖3个CSS属性才能实现这项工作

.question-summary .summary {
    width: auto !important;      /* original = width: 735px; */

    float: none !important;      /* original = float: left; set to 'none' to get the 'overflow' property work */
    overflow: hidden !important; /* original = not set, default is visible */
}

2 个答案:

答案 0 :(得分:5)

您应该将宽度重置为其初始值,即auto

编辑:
正如您所注意到的,为了使width:auto起作用,您还应该重置float属性,否则宽度将不会占用剩余的可用空间。

答案 1 :(得分:4)

像这样写:

.question-summary
    {
        background-color: silver;
        overflow:hidden;
    }
    .statscontainer
    {
        float: left;
        width: 86px;    /* child 1: fixed width */
        margin-right: 8px;
        background-color: gray;
    }
    .summary
    {
        overflow:hidden;
        background-color: lightgray;
    }

选中此http://jsfiddle.net/pGu42/