在页脚前页脚添加边距底部

时间:2015-03-05 18:09:07

标签: html css

我试图查看是否有margin-bottom添加到img元素的方法,只有当footer元素后面跟image-before-footer元素。目前我在我的上一个img元素上使用了一个特殊的类(<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中动态地执行它? / p>

HTML

article {
  margin: 3em 0;
}

img {
  width: 100%;
  vertical-align: middle;
  margin: 0;
}

.image-before-footer {
  margin-bottom: 3em;
}

CSS

{{1}}

对此有任何帮助表示赞赏。提前谢谢!

4 个答案:

答案 0 :(得分:4)

由于您无法在CSS中选择以前的同级元素,为什么不在margin-top元素中添加footer如果它跟在img元素之后使用adjacent sibling combinator, +

Example Here

img + footer {
  margin-top: 3em;
}

您也可以使用:last-of-type pseudo class选择 last img元素。

当然,这假设最后img元素将由footer继承。

Example Here

img:last-of-type {
    margin-bottom: 3em;
}

答案 1 :(得分:1)

您可以使用相邻的兄弟选择器。它将仅选择紧跟在前一个指定元素之后的指定元素。

former_element + target_element { style properties }

根据您的代码,语法为:

img + footer {
    margin-top: 3em;
}

答案 2 :(得分:1)

你可以尝试使用last-of-type伪元素:

img:last-of-type {
margin-bottom: 3em;
}

答案 3 :(得分:0)

试试这个:

http://jsfiddle.net/isqware/g4hxw97m/

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="" 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;
} 
.footer{
background:#000;
width:100%;
min-height:100px;
}

Jquery

$( "footer.footer" ).prev('img').addClass( "image-before-footer" );

我希望它有效。检查JSFiddle示例。

干杯