如何在div中居中图标?

时间:2015-10-23 13:35:56

标签: html css

我正在尝试将标题导航中的图标居中。我有基础知识,但中心会根据同一标题中是否有多个图标而改变。

即使删除左侧或右侧图标,如何保持中心图标居中?

Here is a fiddle demonstrating the issue

HTML

<br>   
<br>   
<div class="mp-myheader">
        <div class="mp-center-wrapper">
            <i class="mp-icon-hamburger mp-icon-xsm mp-float-left"></i>
            <i class="mp-icon-hamburger mp-icon-xsm"></i>
            <i class="mp-icon-hamburger mp-icon-xsm mp-float-right"></i>
        </div>
    </div>

<br>
    <div class="mp-myheader">
        <div class="mp-center-wrapper">
            <i class="mp-icon-hamburger mp-icon-xsm"></i>
            <i class="mp-icon-hamburger mp-icon-xsm mp-float-right"></i>
        </div>
    </div>

CSS

.mp-center-wrapper{
    text-align: center;
}

.mp-myheader {
    background: #015688 !important;
    width:100%
}

.mp-icon-hamburger {
    background-image:       url("http://icons.iconarchive.com/icons/klukeart/summer/128/hamburger-icon.png");
    background-position:center;
    background-repeat:no-repeat;
}

.mp-icon-xsm {
    width: 25px;
    height:25px;
    background-size: 25px;
    display:inline-block;
}

.mp-float-left {
    float:left;
}

.mp-float-right {
    float:right;
}

3 个答案:

答案 0 :(得分:4)

http://jsfiddle.net/es_kaija/7Ln420jo/1/

为您的标题以及左右图标添加position: relative;position: absolute;left: 0; and right: 0;

修正了我的问题。

答案 1 :(得分:0)

&#13;
&#13;
.mp-center-wrapper {
  overflow: auto;
  text-align: center;
}
.mp-myheader {
  background: #015688 !important;
  width: 100%;
  position: relative;
}
.mp-icon-hamburger {
  background-image: url("http://icons.iconarchive.com/icons/klukeart/summer/128/hamburger-icon.png");
  background-position: center;
  background-repeat: no-repeat;
}
.center {
  /* created this new class and applied to middle hamburger icon */
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin: 0 auto;
}
.mp-icon-xsm {
  width: 25px;
  height: 25px;
  background-size: 25px;
  display: inline-block;
}
.mp-float-left {
  float: left;
}
.mp-float-right {
  float: right;
}
&#13;
<br>
<br>
<div class="mp-myheader">
  <div class="mp-center-wrapper"> <i class="mp-icon-hamburger mp-icon-xsm mp-float-left"></i>
    <i class="mp-icon-hamburger mp-icon-xsm center"></i>
    <i class="mp-icon-hamburger mp-icon-xsm mp-float-right"></i>

  </div>
</div>
<br>
<div class="mp-myheader">
  <div class="mp-center-wrapper"> <i class="mp-icon-hamburger center mp-icon-xsm"></i>
    <i class="mp-icon-hamburger mp-icon-xsm mp-float-right"></i>

  </div>
</div>
&#13;
&#13;
&#13;

检查此代码,并阅读CSS中的注释

答案 2 :(得分:-1)

添加保证金:0自动;为您的中间图标(.mp-icon-xsm)

.mp-icon-xsm {
    margin: 0 auto;
}