开发者

How can I have 4 divs inside a div that are all equal in size and are not joined together?

开发者 https://www.devze.com 2023-01-07 07:11 出处:网络
Her开发者_StackOverflow社区e is an example of what I\'m describing: Simple way to achieve the thing you want : use of float:left do work for you

Her开发者_StackOverflow社区e is an example of what I'm describing:

How can I have 4 divs inside a div that are all equal in size and are not joined together?


Simple way to achieve the thing you want : use of float:left do work for you

<div style="width:100%">
 <div style="width:100%">
   <div style="width:45%; float:left">  
      div1
   </div>
   <div style="width:45%; ">  
      div2
   </div>
 </div>
 <div style="width:100%">
   <div style="width:45%; float:left">  
      div3
   </div>
   <div style="width:45%; ">  
      div4
   </div>
 </div>      
</div>


Use float and margin to solve your problem as rahul already suggested. To have 2 floats next to each other use width.

CSS:

.outer {
  border: 1px solid black;
  width: 100%;
  float: left;
}

.inner {
  margin: 10px;
  float:left;
  width:45%;
  border: 1px solid black;
}

HTML:

<div class="outer">
  <div class="inner">div</div>
  <div class="inner">div</div>
  <div class="inner">div</div>
  <div class="inner">div</div>
</div>

I used 45% for the width of the floats, to make sure that they fit. 50% is not working due to the margin. The 45% could be increased slight more I guess, but that depends on the margin of the inner divs.


This could be your HTML:

<div>
    <div>&nbsp;</div>
    <div>&nbsp;</div>
    <div>&nbsp;</div>
    <div>&nbsp;</div>
</div>

And this could be your CSS:

div {
    float: left; /* so the surrounding div takes only the size of its content */
    padding: 20px 0 0 20px; /* to get the same spacing everywhere */
    overflow: hidden; /* this is not needed but i like to use it because clients never do what they shoul :P */
    border: 4px solid black;
}

div > div {
    float: left; /* places the divs next to each other */
    width: 50px;
    height: 50px;
    margin: 0 20px 20px 0; /* makes the space between the divs */
    border: 4px solid black;
}

div > div:nth-child(3n) {
    clear: both; /* you want the 3rd div to start a new line */
}

and this would be the result: http://jsfiddle.net/NgjaY/1/


If you want the divs to be side by side then you can use the float property. If you want seperation between the divs then you can use margin property.


try this code

<html>
<head>
<style type="text/css">
#main   {
    width:130px;
    padding:10px 0px 0px 0px;
    height:auto;
    overflow:hidden;
    background-color:#171817;
}

.div1   {
    width:50px;
    height:50px;
    float:left;
    display:inline;
    margin:0px 0px 10px 10px;
    background-color:white; 
}
</style>
</head>
<body>
<div id="main">
    <div class="div1"></div>
    <div class="div1"></div>
    <div class="div1"></div>
    <div class="div1"></div>
</div>
</body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消