1

As we all know, vertical centering of elements without defining pixel sizes and some math hacks was a huge problem for us in the past with html+css.

As we know have display:grid; and some easy options to center with margin:auto, i found out that not all Elements work out of the box on every browser.

See this demo code : https://jsfiddle.net/2dz7w6L4/

HTML

   <button>
   <img src="https://dummyimage.com/64x64/ff00ff/ffffff.png&text=X">
   <label>Centered Text</label>
   </button>

SCSS

   button{
     border:0; outline:0; margin:0; padding:0;
     padding:1em 1.5em;
     cursor: pointer;

     background-color: green;

     display: grid;
     grid-template-columns: auto auto;
     grid-gap: 1em;

     label{
       font-size: 200%;
       margin: auto;
     }

     img{
       margin: auto;
     }

     &:hover{
       background-color: red;
     }

   }

I love how easy centering ( especially vertical centering ) works for this button and its inner text out of the box. But on my ipad, the Text breaks into another line - so is UNDER the image for no reason. After reading, this is because does not support display:grid at ios.

I wonder, if there is a hack, or another SLICK and MODERN way to build buttons with paddings, various text sizes, and additional elements like images/icons from scratch, without finetuning to make sure the text is vertical centered no matter what browser, font-size. And of cause without forcing things with pixel sizes or negative margins, line-height and stuff.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
scco
  • 139
  • 1
  • 1
  • 9

2 Answers2

0

best solutions is position for support all devices

HTML :

<button class="btn">
        <img src="asset/img/btn.jpg" alt="" class="btn__img">
        <label class="btn__title">center</label>
</button>

SCSS :

.btn {
 position: relative;
 text-align: center;
 border:0; outline:0; margin:0; padding:0;
 padding:1em 1.5em;
 cursor: pointer;
 background-color: green;
&__img {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    z-index: -1;
}

&__title {
    font-size: 200%;
}
&:hover{
    background-color: red;
  }}
amirrr1987
  • 59
  • 6
  • someone please mark this as a duplicate to: https://stackoverflow.com/questions/35464067/flex-grid-layouts-not-working-on-button-or-fieldset-elements – Capagris Sep 13 '20 at 14:31
0

so the best solution i found, is to use a wrapper, and not apply the display:grid to the button, but the wrapper inside the button.

scco
  • 139
  • 1
  • 1
  • 9