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


Tags: css,padding

Problem :

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.



Solution :

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;
}

    CSS Howto..

    How to change color of Bootstrap warning class table row

    How to apply CSS to my JQuery Plugin

    how to center two div in xs

    How to change the opacity background color of other two buttons once we click on a single button using css

    How to selectively pass mouse events to underlying svg elements

    How browser auto resize website to mobile browse?

    CSS/CSS3 - How to make background-color in table row without spaces between table-cells?

    how to write css to reduce font size [duplicate]

    Why the jaggedness at the end? How to fix the CSS style

    How to automatically resize the wrapper div using CSS

    How to refer in CSS to all elements that have some attribute?

    How to make a toggleable navbar in pure CSS?

    How to use CSS position sticky to keep a sidebar visible with Bootstrap 4

    CSS InfoBox over all elements how to place? [closed]

    How do I get css links to resolve correctly when adding a PathInfo value?

    How to produce a green check mark on the menu tabs by using before and after selectors in css ?

    How to make a CSS/javascript feature like this website? [closed]

    How would you switch focus to an input text upon clicking an item on a dropdown menu?

    How to have different transition durations for css and angular transition on same element?

    How not to use body style css rule in part of html code?

    How to put html input text into an image using CSS?

    How to align a link icon after the text via CSS?

    How to keep CSS style If I change the html content dynamically?

    How to display mouseover effect in GridView rows using only CSS?

    How can I change the color of my body when using Bootstrap?

    How can I split this image into pieces so when I write a long text, it doesn't go outside of the div?

    How do align texts in the child div

    How to make rotate photos when you change position iPhones in ios app [closed]

    How do I wrap a overflowed span in fixed div

    How to remove default document style from an element using Javascript