Mario Parra
Mario Parra

Reputation: 1554

Aligning CSS icon with text

I've created a close button in CSS that I'm struggling to align with regular text. Its containing span element appears to align with the adjacent text, but not the children divs.

<a class="event-filter button" href="#">Filter name
  <span class="close-button">
    <div class="menu-bar menu-bar-top"></div>
    <div class="menu-bar menu-bar-bottom"></div>
  </span>
</a>

.close-button {
  display: inline-block;
  position: relative;
  width: 1em;
  height: 1em;
  z-index: 15;
  top: 0;
  left: 0;
  padding: 0;
}
.close-button:hover {
  cursor: pointer;
}
.close-button .menu-bar {
  position: absolute;
  border-radius: 2px;
  width: 100%;
  border: 1px solid grey;
}
.close-button .menu-bar-top {
  border-bottom: none;
  top: 0;
  transform: rotate(45deg) translate(8px, 8px);
}
.close-button .menu-bar-bottom {
  border-top: none;
  top: 22px;
  transform: rotate(-45deg) translate(7px, -7px);
}

http://codepen.io/ourcore/pen/vgXxQG

Upvotes: 0

Views: 64

Answers (2)

allnodcoms
allnodcoms

Reputation: 1262

When justifying text vertically, line-height is your freind:

a {
  padding: 10px;
  background-color: #f3f3f3;
  color: grey;
  line-height: 1em;
  text-decoration: none;
}

.close-button {
  display: inline-block;
  position: relative;
  width: 1em;
  height: 1em;
  z-index: 15;
  top: -2px; /* tweeked your placement a little */
  left: 0;
  padding: 0;

  &:hover {
      cursor: pointer;
    }
}

Setting the anchor's line height to the height of your close box will center the text, vertically, in that space.

Upvotes: 0

Bojangles
Bojangles

Reputation: 101473

Remove display: block and align the close button with vertical-align: middle on the .close-button class. Here is a demonstration.

Setting display: block will cause the close icon to wrap. inline-block behaves as an inlined element, but allows you to set the width and height.

With that fixed, the icon is on the same line but it's not aligned. vertical-align: middle center-aligns (vertically) the button with the text.

Upvotes: 1

Related Questions