Saltssaumure
Saltssaumure

Reputation: 101

Is it possible in CSS to select an element specifically without an ID or class?

I am making a theme for a website, but I ran into a problem. I can't change their HTML or use javascript, only CSS.

This is what the site's HTML looks like:

<div class="container">
  <div style="margin:a ridiculously massive number">
    <p id="title"> Title of page </p>
    <p> Words that cannot be read because of the ridiculous margin </p>
  </div>
  <div id="otherContent"> There a lot of divs without ridiculous margin all with different ids </div>
</div>

I want to remove the ridculous margin without affecting the other divs margins. Is this possible?

Upvotes: 2

Views: 97

Answers (3)

Mouhamad Kawas
Mouhamad Kawas

Reputation: 370

If all the other divs have ID you can use the following:

div>div:not([id]) {
    margin: 0 !important;
}

Upvotes: 0

jmore009
jmore009

Reputation: 12923

yes you can target the div that is the first-child inside of .container as to not effect other divs.

.container div:first-child{
   //code
}

EXAMPLE 1

Example 1 is specifically for the example you posted where the div you would like to target is the first child of it's parent. Also note if the margin is inline like your example you're going to have to over-ride it with !important like so:

.container div:first-child{
   margin: 0 !important;
}

OR

You could also use the :not selector if the other's have a similar class

.container div:not(.classname) {
   //code
}

EXAMPLE 2

The point of example 2 is if your div isn't the first child and the only without a class (it would probably be unlikely you would have multiple divs with the same classname except one but it's possible). in your example you could also use :not() to target that other div with id #otherContent like so:

.container div:not(#otherContent) {
   //code
}

OR

The last option you can use if the others don't apply would be nth-of-type() to target specifically which one you want to effect:

.container div:nth-of-type(2) {
   //code
}

EXAMPLE 3

Upvotes: 4

dfsq
dfsq

Reputation: 193261

In this case you will have to use first-child selector with !important keyword, as this is the only way to make rule more specific than style="margin" rule:

.container > div:first-child {
    margin: 0 !important;
}

Upvotes: 1

Related Questions