问题描述
我试图看看是否有一种方法可以在 img
元素中添加 margin-bottom
如果它后面是一个 footer
元素。目前我在我最后的 img
元素上使用一个特殊类( image-before-footer
$ b b
< div class =container>
< h1>标题在这里< / h1>
< article> Lorem。< / article>
< img src =https://ununsplash.imgix.net/photo-1421284621639-884f4129b61d?dpr=1.80&fit=crop&fm=jpg&h=700&q=75& ; w = 1050/>
< article> Lorem。< / article>
< img class =image-before-footersrc =https://ununsplash.imgix.net/photo-1421284621639-884f4129b61d?dpr=1.80&fit=crop&fm= jpg& h = 700& q = 75& w = 1050/>
< footer class =footer>
< p>这是我的脚注< / p>
< / footer>
< / div>
CSS
article {
margin:3em 0;
}
img {
width:100%;
vertical-align:middle;
margin:0;
}
.image-before-footer {
margin-bottom:3em;
}
任何帮助,谢谢。提前感谢!
由于您不能在CSS中选择先前的同级元素,为什么不添加 margin-top
到页脚
元素 if 后跟 img
元素,使用:
img + footer {
margin-top: 3em;
}
使用。
当然,这假设最后的 img
元素将被 footer
img:最后类型{
margin-bottom:3em;
}
I'm trying to see if there's a way to add a margin-bottom
to an img
element only if it's followed by a footer
element. At the moment I'm using a special class (image-before-footer
) on my last img
element to acheive this, but was wondering if there's a way to do it dynamically in CSS?
HTML
<div class="container">
<h1>Title goes here</h1>
<article>Lorem.</article>
<img src="https://ununsplash.imgix.net/photo-1421284621639-884f4129b61d?dpr=1.80&fit=crop&fm=jpg&h=700&q=75&w=1050"/>
<article>Lorem.</article>
<img class="image-before-footer" src="https://ununsplash.imgix.net/photo-1421284621639-884f4129b61d?dpr=1.80&fit=crop&fm=jpg&h=700&q=75&w=1050"/>
<footer class="footer">
<p>Here are my footnotes</p>
</footer>
</div>
CSS
article {
margin: 3em 0;
}
img {
width: 100%;
vertical-align: middle;
margin: 0;
}
.image-before-footer {
margin-bottom: 3em;
}
Any help with this is appreciated. Thanks in advance!
Since you can't select previous sibling elements in CSS, why not just add a margin-top
to the footer
element if it follows an img
element using the adjacent sibling combinator, +
:
img + footer {
margin-top: 3em;
}
You could also just select the last img
element using the :last-of-type
pseudo class.
Of course, this assumes that the last img
element will be succeeded by the footer
, though.
img:last-of-type {
margin-bottom: 3em;
}
这篇关于在页尾之前将边距添加到图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!