一.使用display:inline;
- 我们可以用display:inline把元素转换为行内元素 但是转为行内元素了他的长度宽度就是它本身内容的长度宽度了 设置属性不起作用
<style>
/* 方法一*/
.box1,
.box2 {
display: inline;
width: 200px;
height: 2000px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">盒子一</div>
<div class="box2">盒子二</div>
</div>
</body>
二.使用display:inlien-block
用display:inline-block;可以放元素在一行显示 但是他会受空格/换行键的影响会有默认的间距
解决办法:
- 可以给加了display:inline-block 父元素添加font-size 但是默认的子元素里面内容会消失 这时候在给子元素添加font-size把父元素的font-size覆盖即可
- 2.去掉空格和换行的影响 但是这样或影响代码的可读性,不规范,不建议使用
<style>
/* 方法二 display: inline-block;*/
* {
padding: 0px;
margin: 0px;
}
.box {
font-size: 0px;
}
.box1,
.box2 {
display: inline-block;
width: 200px;
height: 200px;
font-size: 24px;
text-align: center;
background-color: pink;
}
.box2 {
background-color: red;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">盒子一</div>
<div class="box2">盒子二</div>
</div>
</body>
三.使用浮动float:left/right 但是记得清除浮动 有个最简单的方法就是给父元素添加overflow:hidden
注意:
- 浮动float中间是没有间隙的
- 如果用了浮动display:inline-block就没有效果了
<style>
/* 方法二 浮动float*/
* {
padding: 0px;
margin: 0px;
}
.box {
overflow: hidden;
/* 清除浮动 */
}
.box1,
.box2 {
float: left;
width: 200px;
height: 200px;
text-align: center;
background-color: pink;
}
.box2 {
background-color: red;
}
</style>
</head>
<body>
<div class="box">
<div class="box1">盒子一</div>
<div class="box2">盒子二</div>
</div>
</body>