user4571629
user4571629

Reputation: 450

Set width of div equally with CSS

How can I set those divs to be equally, I gave it first width:50%; bu then I wanted to set a margin for each one, so I set the width to 49% and gave it margin-right:1%; but it doesn't seem right because I have also margin-right on the right


Code:

ul li { 
    list-style-type:none;
    background:#f29;
    width:49%;
    height:100px;
    float:left;  
    margin-right:1%; 
    margin-bottom:1%;
}

Example:
http://jsfiddle.net/bnjv39o3/

Upvotes: 1

Views: 92

Answers (4)

King Size
King Size

Reputation: 397

Use child selectors. Here is the fiddle

ul li { 
list-style-type:none;
background:#f29;
width:49.5%;
height:100px;
float:left;  
margin-bottom:1%;
}

ul li:nth-child(odd)
{ margin-right:0.5%; 
}

ul li:nth-child(even)
{margin-left:0.5%;}

Upvotes: 0

Paulie_D
Paulie_D

Reputation: 114991

You can solve this but adding padding-left & padding-top to the parent

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
body {
  padding: 0;
  margin: 0;
}
ul {
  padding: 0;
  padding-left: 1%;
  padding-top: 1%;
  margin: 0;
}
ul li {
  list-style-type: none;
  background: #f29;
  width: 49%;
  height: 100px;
  float: left;
  margin-right: 1%;
  margin-bottom: 1%;
}
<ul>
  <li>BOX1</li>
  <li>BOX2</li>
  <li>BOX3</li>
  <li>BOX4</li>
  <li>BOX5</li>
  <li>BOX6</li>
</ul>

Upvotes: 0

user3196599
user3196599

Reputation:

Using Flexbox this can be easily accomplished. See this

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

html, body {
  height: 100%;
}

body {
  font-family: sans-serif;
  line-height: 1.4;
}

h1 {
  font-size: 150%;
}

p {
  margin-bottom: 10px;
}

.paddingBlock {
  padding: 20px 0;
}

.eqWrap {
  display: flex;
}

.eq {
  padding: 10px;
}

.eq:nth-of-type(odd) {
  background: yellow;
}

.eq:nth-of-type(even) {
  background: lightblue;
}


.equalHMRWrap {
  justify-content: space-between;
  flex-wrap: wrap;
}

.equalHMR {
  width: 49%;
  margin-bottom: 2%;
}
<div class="paddingBlock">

  <div class="equalHMRWrap eqWrap">
    <div class="equalHMR eq">boo</div>
    <div class="equalHMR eq">shoo</div>
    <div class="equalHMR eq">clue</div>
    <div class="equalHMR eq">boo <br> boo </div>
    <div class="equalHMR eq">shoo</div>
    <div class="equalHMR eq">clue</div>
  </div>
</div>

Upvotes: 1

Dan Gamble
Dan Gamble

Reputation: 4155

You can use box-sizing: border-box which makes the width: 50% take into account the padding & border and then you can remove the margin-right

Upvotes: 2

Related Questions