0

Is it possible to have a CSS rule that matches an element only if it contains a certain child?

Basically I have post content, where there could be inline images. I want all images to be centered but not the text. It looks like there is a patter to the inline images. They appear like this:

<p>Some text</p>
<p>
    <!-- I want this p to be centered since it's an image -->
    <a href="#"><img src="http://fpoimg.com/500x500"/></a>
</p>
<p>Some more text</p>

Is there any possible way without modifying the html to do this solely with some fancy CSS selectors? I know how to do it with jQuery, but I've always been interested if there are some new CSS selectors to help achieve this.

Corey
  • 2,163
  • 4
  • 30
  • 56

3 Answers3

1

try this:

p>a>img{
    display: block;
    margin-left: auto;
    margin-right: auto;
}
imnancysun
  • 592
  • 6
  • 13
0

You can use something like p:nth-child(-n+3) to select elements of a certain type and pattern. (You'd have to create a parent selector though).

You could also use the basic cascade to apply a style to elements:

p img {styles}

see https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child for more info on patterns and how to use nth selectors.

For example:

p:nth-child(2n+1) {
      background-color: lime;
    }


<div>
      <span>This span is limed!</span>
      <span>This span is not. :(</span>
      <em>This one is odd. </em>
      <span>Sadly, this one is not...</span>
      <span>But this one is!</span>
</div>
markthethomas
  • 4,002
  • 2
  • 21
  • 36
0

Tell me if this solves your problem:

p img {
    display: block;
    margin: 0 auto;
}

JSFiddle: http://jsfiddle.net/dpmytcjL/1/

dduupp
  • 301
  • 2
  • 3
  • 10