How to center text on button in different screens

2019-09-26 10:02发布

问题:

I have a problem with button text. when I resize, its text remains no more in center on some screen sizes as in these images.

In iPad, it is good

In iPhone, it is ugly, not centered position

Html

<div class="row">
  <div class="col-lg-12 col-md-12 col-sm-12">
    <div @fade class="img-wrapper">
      <img [src]="imgPath" class="img-fluid">
      <div class="img-overlay">
        <button routerLink="/test" 
                class="btn btn-success fill-container testButton">
                TEST
        </button>
      </div>
    </div>
  </div>
</div>

CSS

.img-wrapper {
    position: relative;
}

.img-overlay {
    position: absolute;
    bottom: 31%;
    left: 13.5%;

    width: 34%;
    height: 4%;
    background-color: red;
}

.testButton {
    font-size: 3vw;
    line-height: 20px;
}
.fill-container {
    width: 100%;
    height: 100%;
}

Please let me know what should I make right to do it right.

Regards

回答1:

The solution is simple: If you don't try to prevent the native Bootstrap 4 classes from working by applying custom css that breaks them, then adding the text-center class is all you need.

Here's a code snippet that shows this class perfectly doing its job:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div class="container">
    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12">
            <div @fade class="img-wrapper">
                <img [src]="imgPath" class="img-fluid">
                <div class="img-overlay text-center">
                    <button routerLink="/test" 
                            class="btn btn-success fill-container testButton">
                        TEST
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

However, if you start adding css hacks that break Bootstrap, then, of course, you'll need even more css hacks to fix the problems caused by the original css hacks.

In this case, I recommend going back to square one, removing all of your custom css and using native Bootstrap 4 classes to accomplish what you need because native Bootstrap 4 classes can do almost everything you'll ever need in terms of layout. No need for any css hacks.