Thursday 20 October 2016

html - When to use CSS + sign




Very easy question. I have been using CSS for a while but rarely use + sigh for my code. Could any one explain what the best time is to use it? I couldn't find anything from Google...Thanks a millions...


Answer



I've found that adjacent sibling selectors are useful when you want to apply special styling to the first element of a series of elements. For example, if you want to style the first paragraph of an article differently from the rest, you could use:



p {
/* styles for the first paragraph */
}

p + p {

/* styles for all other paragraphs */
}


This can replace using class="first" in many situations.



EDIT: Using the first-child pseudo-class would work better for this specific case, since it's supported by a wider range of browsers. (Thanks alex)



You might also want to adjust how certain elements are positioned when next to each other. If you have an unordered list that looks fine on its own, but needs less padding at the top when it's next to a paragraph, you could use:




ul {
padding-top: 1em;
/* Default ul styling */
}

p + ul {
padding-top: 0;
/* special styling for lists that come after paragraphs */
}


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...