Home > Net >  Center Text and put Icon on the right with Tailwind CSS
Center Text and put Icon on the right with Tailwind CSS

Time:09-22

I try to build a sidebar menu with Tailwind CSS. But I am not able to center the icon in same height like the text of the LI-tag.


    <ul id="sidemenu" class="text-center border-b-2 border-gray-200">
      <li class="border-t-2 border-gray-200">
        <div href="#" class="block cursor-pointer block py-3 relative">
          <span class="">Title 1</span>
          <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 absolute right-1 top-1/2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
          </svg>
        </div>
        <ul class="bg-gray-50 border-t-2 border-gray-100">
          <li class="py-2">Sub-Item-1</li>
          <li class="py-2">Sub-Item-2</li>
          <li class="py-2">Sub-Item-3</li>
        </ul>
      </li>
      <li class="border-t-2 border-gray-200">
        <span class=" block py-3 cursor-pointer">Title 2</span>
      </li>
      <li class="border-t-2 border-gray-200">
        <span class=" block py-3 cursor-pointer">Title 3</span>
      </li>
    </ul>

Here is a example how it looks now: https://jsfiddle.net/j6y3sznq/

CodePudding user response:

The class .top-1\/2 is missing the transform property consider adding transform: translateY(-50%) to align it to the center.

.top-1\/2 {
  transform: translateY(-50%);
}

Updated fiddle here

Solution two: Tailwind class name. Just add transform -translate-y-2/4 to the svg element.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.15/tailwind.min.css">
<ul id="sidemenu" class="text-center border-b-2 border-gray-200">
  <li class="border-t-2 border-gray-200">
    <div href="#" class="block cursor-pointer block py-3 relative">
      <span class="">Title 1</span>
      <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 absolute right-1 top-1/2 transform -translate-y-2/4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
      </svg>
    </div>
    <ul class="bg-gray-50 border-t-2 border-gray-100">
      <li class="py-2">Sub-Item-1</li>
      <li class="py-2">Sub-Item-2</li>
      <li class="py-2">Sub-Item-3</li>
    </ul>
  </li>
  <li class="border-t-2 border-gray-200">
    <span class=" block py-3 cursor-pointer">Title 2</span>
  </li>
  <li class="border-t-2 border-gray-200">
    <span class=" block py-3 cursor-pointer">Title 3</span>
  </li>
</ul>

Updated fiddle here

  • Related