我们都知道div是一个块元素,块元素的特点是,独占一行,从上往下排列,但是有时候我们在页面排版的时候需要从左往右横着排列,想要实现这样的效果方法有很多,首先先来看一下,默认情况下的2个div的效果如下
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .box1{ width: 200px; height: 200px; background-color: blue; } .box2{ width: 200px; height: 200px; background-color: deeppink; } </style> </head> <body> <div class="box1">盒子1</div> <div class="box2">盒子2</div> </body> </html>
想要实现从左往右横着排列的效果,如下图
添加了浮动之后,2个盒子会横着从左往右排列.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .box1{ width: 200px; height: 200px; background-color: blue; float: left;/*添加浮动*/ } .box2{ width: 200px; height: 200px; background-color: deeppink; float: left;/*添加浮动*/ } </style> </head> <body> <div class="box1">盒子1</div> <div class="box2">盒子2</div> </body> </html>
方法2:转换为行内块元素,转换为行内块元素之后,因为行内块识别编辑器敲的回车,所以2个盒子水平之间有缝隙,不建议使用这个方法.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .box1{ width: 200px; height: 200px; background-color: blue; display: inline-block;/*转换为行内块元素*/ } .box2{ width: 200px; height: 200px; background-color: deeppink; display: inline-block;/*转换为行内块元素*/ } </style> </head> <body> <div class="box1">盒子1</div> <div class="box2">盒子2</div> </body> </html>
方法3:设置为弹性布局
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; } body{ display: flex;/*设置为弹性布局,弹性布局中主轴默认是水平的,这个时候内部的子元素会横着排列*/ } .box1{ width: 200px; height: 200px; background-color: blue; } .box2{ width: 200px; height: 200px; background-color: deeppink; } </style> </head> <body> <div class="box1">盒子1</div> <div class="box2">盒子2</div> </body> </html>
标签:盒子,同一,color,height,width,background,div,css,200px From: https://www.cnblogs.com/qian-fen/p/17553146.html