我正在尝试制作一个响应式正方形,其宽度大小基于元素的高度(100%)。我相信仅使用CSS是不可能实现的。
正方形的宽度应等于高度(大容器的100%高度。大容器超过屏幕的100%)。比例必须为宽度=高度以保持正方形。
我正在尝试制作一个响应式正方形,其宽度大小基于元素的高度(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>
请看... 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>
对于仅使用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,以达到精确比例。
由于正方形的宽度和高度相同,且您知道正方形的宽度,因此可以将相同的值应用于高度。
如果您可以使用JS,请尝试以下代码:(jQuery)
var wiDth = $('div').css('width'); // get width
$('div').css('height', wiDth); // apply that value to the height
$('div').css('width', $(this).height());
简单吧!只需要用高度替换宽度.. @Sebastien-Gath - Afzaal Ahmad Zeeshan您可以使用JavaScript来实现这一点。我假设您有一个更大的div容器,其中您想要一个正方形,其高度与容器的高度相同。HTML代码如下:
<div id="container">
<div id="square" style="height:100%;">
</div>
</div>
<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>
var totalHeight = 0;
$("#yourContainer").children().each(function(){
totalHeight += $(this).height;
});
$("#yourContainer").css('width', totalHeight + 'px');
我认为这可以是一个适合你的好的“仅CSS”解决方案。 跨浏览器工作。
http://absolide.tumblr.com/post/7317210512/full-css-fluid-squares
很好强调这个不错的CSS规则:
如果垂直填充(和边距)以百分比(%)值指定,则大小是包含元素宽度的百分比。
好的,这里是解决方案。
<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);
}
.container {
width: 100vh;
height: 100vh;
}
padding-bottom
的百分比来实现这一点。 - SLaks