简体   繁体   English

CSS-固定百分比大小

[英]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. 在CSS中,例如,如果将元素的宽度设置为50%,则当我调整页面大小时,它将改变,而不是百分比,而是像素。

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. 只有使用CSS,您才可以使用固定的容器大小,并使用带有百分比的内部元素。

 .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. 如果您需要%-age用户屏幕的年龄,则需要使用JavaScript来获取实际大小,然后修改容器的大小。 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 parent container设置为像px这样的absolute position

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 http://www.w3schools.com/cssref/css3_pr_mediaquery.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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