1 <div class="content">2 <div class="left"></div>3 <div class="center"></div>4 <div class="right"></div>5 </div>
1 body{margin:0;padding:0;}2 .content div{3 width:100px;4 height:100px;5 background:rgb(147,172,213);6 margin:10px;7 }
Method 1: float
1 .content div{float:left;}
The three divs float together, and there is no problem of merging margins on floating elements, so the left and right margins of the center are both 20px.
Method 2: Absolute positioning
1 .content {position:relative;}2 .content div{position:absolute;}3 div.center{top:0;left:110px;}4 div.right{top:0;left:220px;}
Set the parent element to relative and the positioned child element to Absolute, absolute positioning does not take up space, so at this time the three elements will overlap the vertices of the parent element, and then use top and left to layout the left and right margins of 10px.
Method 3: inline-block
1.content div{display:inline-block;}
Change it Change it to an inline block element, but there will be extra spacing between divs and there will be more compatibility issues.
Method 4: Negative margin
1 div.center{2 margin-left:120px;/*100+10*2=120px 以下数值都以center左右margin为10px考虑*/3 margin-top:-110px;/*100+10=110px 要想用margin-top实现上移,则其值为负*/4 }5 div.right{6 margin-left:230px;/*100*2+10*3=230px*/7 margin-top:-110px;/*当center上去之后,原占位空间不存在,right上移,故再移动需要的高度与center一致为100+10=110px。而如果先写right,margin-top就应该上移(100+10)*2=220px*/8 }
When the network speed is slow or the refresh frequency is high, Using negative margin values will cause significant movement, so this method is not recommended.