简体   繁体   中英

Center align span inside anchor tag

    <div>
        <ul>
            <li class="dropdown">
             <a href="link" class="col-xs-12">
                <span class="dropdown-toggle" data-toggle="dropdown">
                    <span id="image" class="col-xs-3"><img src="/home" width="100" height="100" /></span>
                    <span id="display_name" class="col-xs-6">  @Name </span>
                    <span class="caret"></span>
                </span>
              </a>
            </li>
        </ul>
    </div>

I need center span element which contains name is always align at middle of anchor tag. I don't want to set height and line height of the a tag. Because the name length may vary. so a tag height also will differs. Whatever the name entered I need to align it to center. How to achieve this ?

Use this display:table and display:table-cell structure for vertically align it to center.

  a { display: table; } a span { display: table-cell; vertical-align: middle; } 
 <div> <ul> <li class="dropdown"> <a href="link" class="col-xs-12"> <span class="dropdown-toggle" data-toggle="dropdown"> <span id="image" class="col-xs-3"><img src="/home" width="100" height="100" /></span> <span id="display_name" class="col-xs-6"> @Name<br>@Name<br>@Name </span> <span class="caret"></span> </span> </a> </li> </ul> </div> 

In above snippet no matter how long is the name it will automatically align it to center

CSS-tricks has a guide on how to center things, vertically or horizontally.

.parent {
position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

This means that, implemented in your code, it will look like this:

<div>
    <ul>
        <li class="dropdown">
         <a href="link" class="col-xs-12">
            <span class="dropdown-toggle" data-toggle="dropdown">
                <span id="image" class="col-xs-3"><img src="/home" width="100" height="100" /></span>
                <span id="display_name" class="col-xs-6">  @Name </span>
                <span class="caret"></span>
            </span>
          </a>
        </li>
    </ul>
</div>

CSS:

.col-xs-12{
  position: relative;
}
.col-xs-6{
  position: absolute;
  top:50%;
  transform: translateY(-50%);
}

This might need a little tweaking, since the positioning is absolute and you have two other elements, but it should work just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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