简体   繁体   English

离子:如何使div居中?

[英]Ionic: How to center a div?

THE SITUATION: 情况:

I am making an app using Ionic framework . 我正在使用Ionic框架制作应用程序。 In one page i need to display an image. 在一个页面中,我需要显示图像。 This image has to be horizontally centered. 此图像必须水平居中。

ATTEMPT 1: 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: ATTEMPT 2:

Trying with some old css tricks. 尝试一些旧的CSS技巧。

<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? 我怎样才能在离子框架中居中?

You already found your answer but I would do something like that instead: 你已经找到了答案,但我会这样做:

In your css: 在你的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. 这样您就不需要自己调整每个图像了,当您查看HTML时我发现它非常具有描述性。 Also, it is not restricted to a specific image size. 而且,它不限于特定的图像尺寸。

In Ionic Framework 2 you could now use the attribute directives center and text-center for that. Ionic Framework 2中,您现在可以使用属性指令 centertext-center

<ion-row>
  <ion-col text-center>
    <a href="#">My centered text</a>
  </ion-col>
</ion-row>

Your 2nd attempt works if you add the width style. 如果添加width样式,则第二次尝试有效。 The width should be the width of the image. 宽度应该是图像的宽度。

<div style="margin: 0 auto; width:100px">
    <img src=" {{ data.logo }} " alt="" >
</div>

This should work, just add col-center class: 这应该工作,只需添加col-center类:

<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>

To allign a div center, margin 0 auto is still the best option but for this you need to provide a proper space to the div to find the center section of it and therefore you need to provide it some with. 要设置div中心,margin 0 auto仍然是最佳选择,但为此你需要为div提供一个合适的空间来找到它的中心部分,因此你需要提供一些。

Along with margin 0 auto also give a proper width so your div can find a center location of it. 除了margin 0 auto也提供适当的宽度,所以你的div可以找到它的中心位置。

Simple: 简单:

 <div align="center"> <img style="height:100px;width:100px" src="https://upload.wikimedia.org/wikipedia/commons/6/6a/JavaScript-logo.png" /> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM