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,453
  • 4
  • 35
  • 63
  • 1
    since there's no parent selector , you can't do that... – Bhojendra Rauniyar Jan 30 '15 at 19:20
  • http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector –  Jan 30 '15 at 19:24
  • http://stackoverflow.com/questions/4811962/how-to-css-select-element-based-on-inner-html http://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector – abl Jan 30 '15 at 19:25

3 Answers3

1

try this:

p>a>img{
    display: block;
    margin-left: auto;
    margin-right: auto;
}
imnancysun
  • 612
  • 8
  • 14
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,391
  • 2
  • 25
  • 38
0

Tell me if this solves your problem:

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

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

dduupp
  • 291
  • 2
  • 3
  • 11