HTML/CSS - Extend element width to visible area (b

2019-08-08 12:38发布

I have a web page that I'm generating, where there is a h2 with a green background labeling a table. The table can have any number of columns and I would like the h2 element to extend horizontally as far as the user can scroll, so that there is always a green bar above the table. The effect I'm trying to achieve is a green bar that spans at least the width of the table, so that it is always directly above the table, no matter how far the user scrolls.

Here is what it currently looks like (the red outline shows approximately the edges of the containing html, body, and div elements): Screenshot And here are the relevant pieces of code:

css:

h2 {
    font-family:Arial;
    font-size:20pt;
    color:#FFFFFF;
    text-align:left;
    font-weight:normal;
    background-color:#00693C;
    clear: both;
    padding:2px;
    margin: 0px;
}
table.response {
    border:1px outset;
    border-collapse: separate;
}
table.response td {
    font-size: 14px;
    padding: 3px;
    border:1px inset;
}

html:

<h2>[snip]</h2>
<table class="response">
  <tbody>
    <tr>
      <td>[snip]</td>
      [...]
    </tr>
    [...]
  </tbody>
</table>

Things I have tried already that haven't worked:

  1. A <thead> element containing a single <tr> and a single <th> where the colspan on the <th> is set to the number of columns in the table. This works for smaller numbers of columns, but for larger tables (for example, with colspan="6000"), some browsers (specifically, Firefox 11) render the cell (and its background) as only taking up one column.
  2. A <thead> element containing a single <tr> and one <th> with colspan="2" and the background-color CSS property set for the <tr> element. Using Firefox's Inspect Element feature, it showed that the <tr> spanned the entire width of the table, but the background was only applied to the one cell.
  3. A <thead> element containing a single <tr> and one <th> with colspan="2" and another <th> for every remaining column of the table. I tried to remove the separation between cells on the <thead>, but I was unable to.

My question is this: Is there a way to achieve the effect of having the green bar extend at least the entire width of the table, and if so, what is it? I would prefer not to use JavaScript or have to generate style code when I generate the HTML for the table.

标签: html css layout
2条回答
爷、活的狠高调
2楼-- · 2019-08-08 12:55

Add

div#container { display: inline-block; }

To your CSS, and embed the <h2> and <table> inside a DIV with that name:

<div id='container'>
  <h2>...</h2>
  <table>
    ...
  </table>
</div>

That should work in any modern browser.

查看更多
地球回转人心会变
3楼-- · 2019-08-08 13:13

Add float: left or display: inline-block to the element that contains the table and h2.

查看更多
登录 后发表回答