user927797
user927797

Reputation:

How do I apply a css padding to one element but not its child

Given the following code

<div class="container">
  <p>Some Text</p>
  <p><img src="image.jpg"><p>
  <p>More Text</p>
</div>

CSS

.container {
  width: 640px;
}

.container p {
  padding: 10px 20px;
}

When there's an image, i don't want it to inherit the padding from the p. How can I do this? Keep in mind, I cannot change the actual html, just the css.

Upvotes: 1

Views: 7270

Answers (2)

Sander Declerck
Sander Declerck

Reputation: 2555

Not sure what you mean. Padding isn't inheritted...

Do you mean you don't want the p that contains an img tag to have the padding?

You could try this:

HTML:

<div class="container">
  <p>Some Text</p>
  <p><div class="center"><img src="afb.png"></div><p>
  <p>More Text</p>
</div>

CSS:

.container {
  width: 640px;
}

.container p {
  padding: 10px 20px;
}

.container p img {
  margin: -10px -20px;
}

.center{
  text-align:center;
}

Upvotes: 6

Daniel Casserly
Daniel Casserly

Reputation: 3480

You can add another css rule that overrides the second one

.container p img
{
   padding : 0 0;
}

Upvotes: 0

Related Questions