day6 相对定位:position:relative
相对定位:position:relative
特点:a.相对于自己原来位置的定位,以自己的左上角为基准。
b.相对定位原来的位置仍然算位置,不会出现浮动现象。
以下为初始位置:(可以看出设置margin和position的区别)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>相对定位</title> <style> * { margin: 0; padding: 0; } .top { height: 100px; width: 100px; margin: 50px; background-color: pink; /* position: relative; top:100px; bottom: 100px; */ } /* .bottom { height: 100px; width: 120px; background-color: yellow; } */ </style> </head> <body> <div class="top"></div> <div class="bottom"></div> </body> </html>
效果图如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>相对定位</title> <style> * { margin: 0; padding: 0; } .top { height: 100px; width: 100px; margin: 50px; background-color: pink; /* 设定相对位置 */ position: relative; top:100px; bottom: 100px; } /* .bottom { height: 100px; width: 120px; background-color: yellow; } */ </style> </head> <body> <div class="top"></div> <div class="bottom"></div> </body> </html>
设定相对定位之后的效果图:
top设置相对定位,bottom不设置定位:
初始状态如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>相对定位</title> <style> * { margin: 0; padding: 0; } .top { height: 100px; width: 100px; background-color: pink; /* 设定相对位置 position: relative; top:100px; bottom: 100px; */ } .bottom { height: 100px; width: 100px; background-color: yellow; } </style> </head> <body> <div class="top"></div> <div class="bottom"></div> </body> </html>
效果图如下:
设定了相对定位后:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>相对定位</title> <style> * { margin: 0; padding: 0; } .top { height: 100px; width: 100px; background-color: pink; /* 设定相对位置 */ position: relative; top:100px; bottom: 100px; } .bottom { height: 100px; width: 120px; background-color: yellow; } </style> </head> <body> <div class="top"></div> <div class="bottom"></div> </body> </html>
效果图如下:
加油!