[英]Div Square, width size based on 100% height
我正在尝试根据元素的(100%)高度制作一个宽度大小的响应式正方形。 我相信只使用 CSS 是不可能的。
正方形的宽度应该等于高度(大容器的 100%。大容器超过屏幕的 100%)。 该比率必须是宽度=高度才能保持正方形。
你可以用一个很小的内联图像来做到这一点。 没有 JS,没有额外的文件。
.container { height: 150px; width: 100%; text-align: center; background: #acd; } .square { display: inline-block; height: 100%; background: #691; }
<div class="container"> <div class="square"> <img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" height="100%"> </div> </div>
对于仅使用 CSS 的解决方案(相对于屏幕大小调整大小),请使用viewport units 。 例如:
@media screen and (orientation:landscape) {
.box{
height: 100vh;
width: 100vh;
}
}
@media screen and (orientation:portrait) {
.box{
height: 100vw;
width: 100vw;
}
}
(您可能希望将其减少到 98 个单位以消除滚动)
非常适合需要占用精确比例屏幕空间的 div。
我认为这对您来说可能是一个很好的“仅 css”解决方案。 跨浏览器工作。
http://absolide.tumblr.com/post/7317210512/full-css-fluid-squares
很高兴突出这个漂亮的 CSS 规则:
如果垂直填充(和边距)以百分比 (%) 值指定,则大小是包含元素宽度的百分比。
由于正方形具有相同的宽度和高度,并且您知道正方形的宽度,因此可以将相同的值应用于高度。
如果你可以使用 JS,那么请试试这个:(jQuery)
var wiDth = $('div').css('width'); // get width
$('div').css('height', wiDth); // apply that value to the height
在这里试试:http: //jsfiddle.net/afzaal_ahmad_zeeshan/vpGUK/
您可以使用 javascript 完成此操作。 我假设你有一个更大的 div 容器,你想要一个正方形,它的高度与容器的高度相同。 html如下:
<div id="container">
<div id="square" style="height:100%;">
</div>
</div>
在 javascript 中,您只需执行以下操作:
<script>
var container = document.getElementById("container");
var square = document.getElementById("square");
square.style.width = container.style.height;
window.onresize=function(){
square.style.width = container.style.height;
};
<script>
希望有帮助
把它放在你的<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
并尝试使用 jquery:
var totalHeight = 0;
$("#yourContainer").children().each(function(){
totalHeight += $(this).height;
});
$("#yourContainer").css('width', totalHeight + 'px');
好的,这里的解决方案。
<div id="square" style="background-color:black;height:100%">test</div>
$(window).ready(updateWidth);
$(window).resize(updateWidth);
function updateWidth()
{
var square = $('#square');
var size = square.height();
square.css('width',size);
}
看一看……查看aspect-ratio
属性。
这个属性可以用最简单的方法根据高度创建一个方形 div。 这是一些示例代码:
h2 { font-family: calibri; } #parent { height: 96px; width: 256px; background: grey; margin-bottom: 16px; } #child { height: 80px; aspect-ratio: 1 / 1; background: lightgrey; } #anotherParent { height: 96px; width: 256px; background: grey; } #anotherChild { height: 50%; aspect-ratio: 1 / 1; background: lightgrey; }
<h2>Absolute height (80px/96px)</h2> <div id="parent"> <div id="child"> </div> </div> <h2>Relative height (50%)</h2> <div id="anotherParent"> <div id="anotherChild"> </div> </div>
这里有几个链接可以帮助您理解宽高比属性:
您可以像这样为容器分配宽度和高度
.container{
width: '100vh',
height: '100vh',
}
它将创建一个高度为 100% 且宽度=高度的方形 div。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.