简体   繁体   中英

CSS - Fixed percent size

In CSS, if I set the width of an element to 50% for example, it will change when I resize the page, not in percent, but in pixels.

Is there any way to set an elements width to a certain percent of the page, but ensure that it won't change when the page is resized?

Only with CSS you're able to just use fixed container size, and inner elements with percentages.

 .container { width: 500px; } .innerDiv { width: 49%; float: left; text-align: center; background-color: #ccc; margin-left: 5px; } 
 <div class="container"> <div class="innerDiv"> Div 1 </div> <div class="innerDiv"> Div 2 </div> </div> 

In case that you need %-tage of the user's screen, then you'll need to use JavaScript to fetch the actual size and then modify the container's size. Here is an example for that too:

 $(document).ready(function() { $('.container').width($(window).width()); }); 
 body { margin: 5px 0; } .container { width: 500px; } .innerDiv { width: 49%; float: left; text-align: center; background-color: #ccc; margin-left: 5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="innerDiv"> Div 1 </div> <div class="innerDiv"> Div 2 </div> </div> 

set parent container to absolute position like px

and inside the container set your layout in % value..

It's So simple use media queries for it. http://www.w3schools.com/cssref/css3_pr_mediaquery.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM