Parent element take child size in css

空扰寡人 提交于 2019-12-25 02:18:14

问题


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 !


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/21783721/parent-element-take-child-size-in-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!