Ionic: How to center a div?
Solution 1
In Ionic Framework 2 you could now use the attribute directives center
and text-center
for that.
<ion-row>
<ion-col text-center>
<a href="#">My centered text</a>
</ion-col>
</ion-row>
Solution 2
You already found your answer but I would do something like that instead:
In your css:
.center {
margin-left: auto;
margin-right: auto;
display: block;
}
And then just add this class to your image:
<img src="{{ data.logo }}" class="center" alt="">
This way you don't need to adjust each image on its own and I find this very descriptive when you look at the HTML. Also, it is not restricted to a specific image size.
Solution 3
Your 2nd attempt works if you add the width
style. The width should be the width of the image.
<div style="margin: 0 auto; width:100px">
<img src=" {{ data.logo }} " alt="" >
</div>
Solution 4
This should work, just add col-center
class:
<div class="row">
<div class="col col-33"></div>
<div class="col col-33 col-center">
<img src="{{ data.logo }}" alt="">
</div>
<div class="col col-33"></div>
</div>
Solution 5
Simple:
<div align="center">
<img style="height:100px;width:100px" src="https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png" />
</div>
FrancescoMussi
Full-stack developer based in Riga, Latvia. Hope Socrates is proud of my Socratic badge on StackOverflow.
Updated on May 12, 2020Comments
-
FrancescoMussi almost 4 years
THE SITUATION:
I am making an app using Ionic framework. In one page i need to display an image. This image has to be horizontally centered.
ATTEMPT 1:
Following the documentation i have divided one row into three equal columns and put the image in the second one.
<div class="row"> <div class="col col-33"></div> <div class="col col-33"> <img src="{{ data.logo }}" alt=""> </div> <div class="col col-33"></div> </div>
But unfortunately the image is far to be centered. Tend to stay in the left half of the screen.
ATTEMPT 2:
Trying with some old css tricks.
<div style="margin: 0 auto;"> <img src=" {{ data.logo }} " alt="" > </div>
But again i am not getting the desired result.
THE QUESTION:
How can i center a div in Ionic framework?
-
FrancescoMussi almost 9 yearsOk, will require some extra work to get the width of each image but seems working properly. Strange is not contemplated in Ionic grid system no?
-
wassimans over 8 years"col-center" is for vertical centring.