1

I have written a class for a textfield with a certain style. The field appears at 2 very different place within the website, with different parent elements. The second need another margin-top. What is an efficient way to change the original margin-top, since I cannot use pseudo-classes?

js fiddle

HTML

<div class="some_parent">
  <div class="my_styled_field"></div>
</div>
 .....

<div class="some_other_parent">
  <div class="my_styled_field"></div>
</div>

CSS

.my_styled_field{
    margin-top: 2rem;

}

4 Answers 4

3
.some_other_parent .my_styled_field{
margin-top:3em; //what ever you want
}

this is the way to apply some other styles to the same class, having different parents .

Sign up to request clarification or add additional context in comments.

Comments

2

Pretty sure the most efficient way - most of the time - as in best performance, would be to add another class to your second styled_field.

If you add another class to your second styled_field, you would need only 1 reflow to reach it:

.newclass{margin-top:5px;}

Whereas using the descendant selector which others are selecting is surely worse performance, this means the browsers has to check a lot of elements recursively:

.parent .styled_field

If you don't want to add a class for some reason, better performance than the descendant selector would be the child selector:

.parent > .styled_field

When thinking about css performance, remember that even though we read left-to-right, browsers read right-to-left.

Where we would check all .container elements for an image-tag, browsers find all image-tags - then checks if they are in a .container

Comments

2

Using CSS class hierarchy:

.some_other_parent .my_styled_field {
   margin-top: 2em; 
}

Comments

1

Youc can do this:

FIDDLE EXAMPLE

.some_parent .my_styled_field{
    width: 3rem;
    height: 3rem;
    margin-top: 2rem;
    background-color: red;
}
.some_other_parent .my_styled_field{
    width: 4rem;
    height: 4rem;
    margin-top: 4rem;
    background-color: green;
}

This way, you aply style to .my_styled_field depending on his parent element.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.