0

I'ld like to have a parent element take it's child size. The problem is that I need the child element's width to be defined in percent (for it to be responsive).

I can't set the parent element to be 50% for example, because only the child has the class I need and the block size varies by this class. I am using isotope so some of this code can't be changed.

Here's an example code :

<div class="parent">
   <div class="child size1">content</div>
</div>

<div class="parent">
   <div class="child size2">content</div>
</div>

CSS :

.parent{
float: left;
margin: 0px 5px 10px 5px;
position: absolute;
left: 0px;
top: 0px;
-webkit-transform: translate3d(0px, 796px, 0px);
z-index: 20;
}

.size1{
width: 25%; /*I need the parent to take this size also -> 25% of the page */
}

.size2{
width: 50%; /*I need the parent to take this size also -> 50% of the page */
}

Anyone has a CSS solution ? If I can't figure it out, I'll use jquery but I don't want my website to get unnecessary js if there's an other solution....

Thanks !

Matoma16
  • 1
  • 4
  • possible for you to use pseudo classes? f.e.: parent:nth-child(n) – ggzone Feb 14 '14 at 16:06
  • I don't think so as the size needed is variable (not constantly size1 then size2 then again size1 etc.), and what I understand with nth-child is that for example I can set every 4th element to be a certain width ? maybe I didn't understand how it works though. – Matoma16 Feb 14 '14 at 16:21

2 Answers2

0

This can't be done with CSS the way you are hoping - percentage widths are percentages of their parent's container. let's say the parent is 1000px wide. size1 would be 250px (25%). If at this point you change the parent to be 250px, size1 will become 62.5px (25% of 250px). hopefully that makes sense.

willanderson
  • 1,458
  • 12
  • 13
  • the only way a parent and its child will be the same width if defined in percentages is if the child is set to 100% width, and even then it's 100% of the parent's width, not 100% of the page. – willanderson Feb 14 '14 at 16:16
  • Ok thanks for your reply. I was hoping there was a way I didn't know. I'll use jquery then. Thanks for your answer ! – Matoma16 Feb 14 '14 at 16:22
0

You can use the vw and vh units. These essentially correspond to a percentage of the page width and height respectively.

For example, in your code

.size1{
width: 25%; /*I need the parent to take this size also -> 25% of the page */
}

Change width: 25%; to width: 25vw;

This makes each element in the .size1 class 25% the width of the page regardless of the element it is nested inside.

Nick
  • 305
  • 1
  • 2
  • 5