div套路之div悬浮

没有什么问题是用一个div解决不了的,如果有,那就用两个。

项目终于提测了,耗时3周,经历了从前端小白到前端小菜的过程。在开发过程中,踩到了很多坑,但是通过万能的baidu和google,这些坑都被填平了,尽管填坑的材料可能不是最优。现在纪录一下踩到的坑和填坑的过程。

Requirement:
实现一个在图片底部用阴影展示title的样式。如果把图片和标题各看作一个div,那要实现的就是让一个div悬浮(或重叠)在另一个div上面。

Implementation:
1、按顺序输入的div是从上到下排列的。

html:
    

title

css: .under {width: 100px; height: 50px; background: #bebebe;} .over {width: 100px; height: 30px; background: black; color: white;}

效果:

div套路之div悬浮_第1张图片
Paste_Image.png
  • 上方灰色区域为under,下方黑色区域为over,按顺序排列。

2、为了让over悬浮在under上,要使用到position属性。

html不变。
css:
    .under {width: 100px; height: 50px; background: #bebebe; position: absolute;}
    .over {width: 100px; height: 30px; background: black; color: white; position: relative;}

效果:

div套路之div悬浮_第2张图片
Paste_Image.png
  • 此时over已经悬浮在under上了。通过调整over的top属性,即可调整over在under上的位置。
  • 但是此时有一个问题,如果要将over固定在under底部,要设置top: 20px;或者bottom: -20px;才行。因为此时under是绝对位置,over是相对位置,此时的top和bottom均为over自身的顶部的底部。如果under的高度是不固定的,此时over的位置就很难确定了。接下来我们就解决这个问题。

3、没有什么问题是一个div解决不了的。

html:
    

title

css: .parent {position: relative;} .under {width: 100px; height: 50px; background: #bebebe;} .over {width: 100px; height: 30px; background: black; color: white; position: absolute; bottom: 0;}

效果:

div套路之div悬浮_第3张图片
Paste_Image.png
  • 通过使用一个父div将under和over包括起来,并将父div设置为relative,over为absolute。此时over的位置即是相对父元素的位置。

好了。今天就纪录到这里,如果找到更好的方法会继续补充。加油!新的一周已经开始!

你可能感兴趣的:(div套路之div悬浮)