Jarlik Stepsto
Jarlik Stepsto

Reputation: 1745

CSS: set width exact equal to content

I am searching for a way, to make a div as width as its biggest child.

Situation:

<container>
  <div1></div1>
  <inner_container>
    <item1>
    <item2>
    <item3>
    ...
  </inner_container>
</container>

https://jsfiddle.net/hmman06s/1/

Note:

item width is fix (using background image)
item margin is fix
container width is in %

Now i want, that div1 is as width, as the line of items of inner_container. Like in this image:

enter image description here

But using inline-block, depending on screen width, i get something like this: See the green extra space:

enter image description here

Is the a css-only way, to do this?

Thank you for your help!

Upvotes: 2

Views: 1320

Answers (2)

Rounin
Rounin

Reputation: 29511

You can achieve the effect you are after, using CSS @media queries.

If your container is 24px less wide than the viewport width and the inner_container is 120px less wide than the container, then the inner_container will always be 144px less wide than the viewport.

If your item is 80px wide and has a margin either side of 10px, then you will only want the inner_container to expand, every time its inner width reaches a multiple of 100px.

If we add in padding of 12px to the left and the right of the row of items (making the inner_container another 24px wider), we now have enough information to calculate all the viewport breakpoints:

  1. Ten items requires a viewport of 1168px (10 x 100px + 24px + 144px)
  2. Nine items requires a viewport of 1068px (9 x 100px + 24px + 144px)
  3. Eight items requires a viewport of 968px (8 x 100px + 24px + 144px)
  4. Seven items requires a viewport of 868px (7 x 100px + 24px + 144px)
  5. Six items requires a viewport of 768px (6 x 100px + 24px + 144px)
  6. Five items requires a viewport of 668px (5 x 100px + 24px + 144px)

Consequently:

@media only screen and (max-width: 1267px) {  /* 10 items */
inner-container {width: 1024px;}
}

@media only screen and (max-width: 1167px) {  /* 9 items */
inner-container {width: 924px;}
}

@media only screen and (max-width: 1067px) {  /* 8 items */
inner-container {width: 824px;}
}

@media only screen and (max-width: 967px) {  /* 7 items */
inner-container {width: 724px;}
}

@media only screen and (max-width: 867px) {  /* 6 items */
inner-container {width: 624px;}
}

@media only screen and (max-width: 767px) {  /* 5 items */
inner-container {width: 524px;}
}

Upvotes: 1

caldera.sac
caldera.sac

Reputation: 5108

hope this will help to you. in your style change these widths

.icon {
  display: inline-block;
  background-color: grey;
  width:100%;
}

.item {
  width:9%;
  height: 50px;
  display: inline-block;
  margin-left:0.09%;
  background-color: red;

}

NOTE: it is simple logic, what you have to do is item-width= full-width/number_of_items_you_want in your case item_width = 100/11

Upvotes: 0

Related Questions