Veer7
Veer7

Reputation: 21513

How to restrict style to only part of HTML

Consider:

<style type="text/css">
    table
    {
        border-collapse: collapse;
    }

    table, td, th
    {
        border: 1px solid green;
    }

    th
    {
        background-color: green;
        color: white;
    }
</style>

I want to apply this to only a single table in an HTML page which has other tables as well. I don't want to use this style for those tables.

Can we really do what I am asking?

Upvotes: 0

Views: 3696

Answers (5)

U.P
U.P

Reputation: 7442

You can create a class and use it for the table you want the styles to work on:

table.myStyles
{
    border-collapse:collapse;
}

table.myStyles, .myStyles td, .myStyles th
{
    border:1px solid green;
}

.myStyles th
{
    background-color:green;
    color:white;
}

Then for your table

<table class="myStyles">....</table>

Upvotes: 1

Luca
Luca

Reputation: 9745

Use:

<style type="text/css">
    table.myTable
    {
        border-collapse: collapse;
    }

    table.myTable, table.myTable td, table.myTable th
    {
        border: 1px solid green;
    }

    table.myTable th
    {
        background-color: green;
        color: white;
    }
</style>

And then change that table to have a class attribute like this:

<table class="myTable">

Upvotes: 4

Dennis Traub
Dennis Traub

Reputation: 51684

<style type="text/css">
  .green-table {
    border-collapse:collapse;
  }
  .green-table td, .green-table th {
    border:1px solid green;
  }
  .green-table th {
    background-color:green;
    color:white;
  }
</style>

<table class="green-table">
    ...
</table>

Upvotes: 0

gordy_gekko
gordy_gekko

Reputation: 31

This is quite easy to do. Just give the table an id, and reference that idea using the '#' in your css code.

Upvotes: -1

Moin Zaman
Moin Zaman

Reputation: 25465

You will need to do one of the following:

  • modify the table's html to give the table and ID or a class, then modify your CSS to table.foo
  • target the table only if it is the first or the last table inside a container using :first-child, :last-child

Upvotes: 0

Related Questions