Roni Litman
Roni Litman

Reputation: 1001

how to maintain percentage width with margins

I have a floated list that contains 3 boxes with the same height. I gave each of them width of 33.333% to get them equaled and to fill the whole container.

I have to get the middle box margined both sides with 5px and because of that my 33.333% gets more than 100%.

I know I can use calc(100% - 5px) and solve this, but the problem is that I don't want any margins for the outer boxes, just for the middle box. With that method I get 5px margin left for the left box.

.highlights-list {
width: 30%;
position: relative;
overflow: hidden;
border: 2px solid lime;
padding: 0;
}
.highlight {
    width: calc(33.333%- 5px);
    text-align: left;
    opacity: 0.9;
    float: left;
    padding: 5px;
    list-style-type: none;
    background: red;
    margin-left: 5px;
}

You can see my whole fiddle here.

Upvotes: 1

Views: 349

Answers (4)

Lucian
Lucian

Reputation: 644

Add box-sizing: border-box; to .highlight, change margin-left to margin: 2px; and set width: calc(33.333% - 4px);

.highlight {
    width: calc(33.333% - 4px);
    box-sizing: border-box;
    text-align: left;
    opacity: 0.9;
    float: left;
    padding: 5px;
    list-style-type: none;
    background: red;
    margin: 2px;
}

Fiddle: http://jsfiddle.net/13j4qqqe/7/

Upvotes: 0

Paulie_D
Paulie_D

Reputation: 115296

Much simpler with flexbox

.wrap {
  width: 500px;
  display: flex;
  border: 1px solid red;
  margin: auto;
}
.box {
  height: 150px;
  flex: 1;
  border: 1px solid green;
}
.wrap > div:nth-child(2) {
  margin: 0 5px;
}
<div class="wrap">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>

Upvotes: 4

Ori Drori
Ori Drori

Reputation: 192857

The simple solution will be to override the margin related settings for the 1st child:

.highlight:first-child {
    width: 33.333%;
    margin-left: 0;
}

Upvotes: 0

Cheslab
Cheslab

Reputation: 1924

The solution is pretty simple - http://jsfiddle.net/13j4qqqe/3/

.highlight:nth-child(2) {
    width: calc(33.333%- 10px);
    margin: 0 5px;
}

Upvotes: 0

Related Questions