How to make the height of an element equal to its width in Ionic?

I am making an application with Ionic and I want to have a square image as the background. The image needs to be scaled for different resolutions; I want it to fill the width of the device, and then be so tall that it has such a width while maintaining the aspect ratio.

I tried to add a directive to calculate the correct height for the installation, but I can not get it to do anything, it does not seem to be called at all.

HTML

<ion-view view-title="Home" > <ion-content class > <div id = "card" ng-model = "card"> <h3>{{card.name}}</h3> </div> </ion-content> </ion-view> 

CSS

 #card{ background-image: url("/img/education.png"); background-size: 100% 100%; width : 100%; } 

Javascript (controllers.js)

 .directive("card", function($scope) { console.log("Card directive called."); return { restrict: "E", link: function (scope, element) { console.log("Link Called"); element.height = element.width; } } }) 
+5
source share
2 answers

The background image will not determine the size of the element as <img> . You have 2 options:

  • Use <img> instead of background-image . This forces the element to adjust the image size (assuming the image is square).

  • Use a bit of complex CSS. Suppose you want a .square element .square be 50% of its parent's width. Assign it a width of 50% , a height of 0 and a padding-bottom of 50% .

     .square { width:50%; height:0px; padding-bottom:50%; background-size: 100% 100%; } 

Here is a demo .

+3
source

Another css solution is vw units.

100% of the viewing screen is 100vw, so setting the height to 100vw will make the height the same as the widescreen view, resulting in a square image.

Here are a few more details.

Here is browser support

0
source

All Articles