I have text content and images mixed and want to apply css margin to elements directly before and after images (
, , can come before or after the image, but I have no control on which one and where)
I am using the following code to apply margin to the elements before the image
#single-pg * + img { margin-top: 75px; }
Problem is that it adds the margin-top to other images aswell (I want it to apply to all elements EXCEPT images) and I want to add similar to affect content elements after the image
#single-pg img + * { margin-bottom: 75px; }
html (Wordpress)
<div id="single-pg" >
<?php the_content(); ?>
</div>
so the outcome could be (but could also be in any other order based on the author)
<h2>Title</h2>
<image></image>
<image<</image>
<p>text</p>
<p>text</p>
<p>text</p>
<image<</image>
Not entirely clear from your description of the issue (and it's hard without seeing your markup); however, if you want margin-top
and margin-bottom
to apply to every element except for images, I'd make use of the :not
selector.
:not(img) {
margin-top: 75px;
margin-bottom: 75px;
}
To target the paragraphs in a more nuanced way, we'll have to use some scripting. We can use the adjacent sibling selector to add our margin-top
value:
img + p {
margin-top:75px;
}
and then we can use the jQuery .prev()
method to target the paragraph immediately preceding each image:
$("img").prev().css("margin-bottom", "75px");
Here is an updated fiddle of an example in action. Let me know if that helps.
将图像和文本放入包装器中,将每个图像和文本放入另一个包装器中,就可以管理每个图像的边距。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.