Grow your CSS skills. Land your dream job.

Child and Sibling Selectors

  • # November 26, 2012 at 4:41 pm

    I have been trying to figure out how to remove the margin-top on the first paragraph which appears on a page under an H1 with the class of entry-title I was reading http://css-tricks.com/child-and-sibling-selectors/ but couldn’t figure it out.

    Here is the html and css on pastebin (couldn’t get it work work in the forum)

    http://pastebin.com/rjGu2aPv

    However that is doing nothing to affect the first paragraph under the H1 tag. What am I doing wrong?

    Thanks,

    Chad

    # November 26, 2012 at 5:08 pm

    I’ve put together a quick jsfiddle: http://jsfiddle.net/TNKtQ/

    In your pastebin link, the paragraph element isn’t a sibling of the h1. The div is the sibling and the paragraph is the child of that sibling.

    So the jsfiddle example will apply those styles to the first paragraph within .testimonial-data as long as it is an adjacent sibling of the h1.

    Also, in the pastebin link you have a typo in the following CSS selector:

    h1.entry-title + p.testimonial-cotent

    # November 26, 2012 at 5:11 pm

    Hi @aeboi80

    I have noticed in your pastebin that you have mis-spelled content in the CSS. Also you have put a ‘+’ to seperate the two selectors, when with CSS syntax you should use a comma (I think?) try and make them changes and see what you get…

    # November 26, 2012 at 5:12 pm

    Okay, so there are a couple of things to consider with this. The first is that the direct sibling of the h1 is actually the div, so the sibling selector won’t work in this case. I get caught out a lot with this, but I have try not to use sibling or child selectors if I can avoid it, as targeting via specific classes is much easier to work with.

    Secondly, you should always try and work with your margins in a single direction only (I generally always use margin-bottom). Here is an example of what I’m talking about: http://jsfiddle.net/joshnh/ZBgYA/

    If you wanted to now remove the margin between the h1 and the p, you could easily do so. Also, you will find that it is much easier to move elements around if the margin is always in one direction. Your code becomes much more modular.

    Lastly, you want to consider vertical rhythm. Here is an article I wrote a while ago on how to set up a baseline grid: http://joshnh.com/2011/08/03/how-to-set-up-a-baseline-grid/

    If you have any other questions, just let me know!

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".