Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an element's height equal to its width in Ionic?

I am making an app with Ionic and I want to have a square image as a background. The image needs to be scaled for different resolutions; I want it to fill the width of the device and then be however high it is at that width while keeping the aspect ratio.

I have tried adding a directive in order to calculate the correct height to set but I can't get it to do anything, it doesn't 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;
        }
   }
})
like image 384
koreus737 Avatar asked Aug 10 '15 20:08

koreus737


People also ask

In which element I can not set height and width?

Inline elements have no width or height property; correct.

How can you change the height of an element?

To change the height of a HTML Element using JavaScript, get reference to this HTML Element element, and assign required height value to the element. style. height property. In the following example, we will change the height of HTML Element with id "myElement" to "150px" , in JavaScript, using element.


1 Answers

A background image will not define the size of an element as an <img> would. You have 2 options:

  1. Use an <img> element instead of background-image. This will cause the element to adjust to the size of the image (assuming the image is square).

  2. Use a bit of tricky CSS. Assume you want the .square element to be 50% the width of it's parent. Assign it a width of 50%, a height of 0 and padding-bottom of 50%.

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

Here's a demo.

like image 116
Brett DeWoody Avatar answered Sep 28 '22 09:09

Brett DeWoody