简体   繁体   English

在图片前的内容上应用CSS边距

[英]Applying css margin to content before images

I have text content and images mixed and want to apply css margin to elements directly before and after images ( 我混合了文字内容和图片,并想将CSS边距直接应用于图片前后的元素(

, , 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) 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. 但是,如果您希望将margin-topmargin-bottom应用于除图像之外的每个元素,则可以使用:not选择器。

:not(img) {
    margin-top: 75px;
    margin-bottom: 75px;
}

EDIT 编辑

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: 我们可以使用相邻的兄弟选择器来添加我们的margin-top值:

img + p {
  margin-top:75px;
}

and then we can use the jQuery .prev() method to target the paragraph immediately preceding each image: 然后我们可以使用jQuery .prev()方法来定位每个图像之前的段落:

$("img").prev().css("margin-bottom", "75px"); 

Here is an updated fiddle of an example in action. 这是一个实际示例的更新小提琴 Let me know if that helps. 让我知道是否有帮助。

将图像和文本放入包装器中,将每个图像和文本放入另一个包装器中,就可以管理每个图像的边距。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM