Vertically center text in Bootstrap carousel

后端 未结 4 900
無奈伤痛
無奈伤痛 2021-01-05 14:09

I have trouble creating a carousel in Bootstrap 4 with text centered both horizontally and vertically.

I have created the bootply with a carousel, but the text is ju

相关标签:
4条回答
  • 2021-01-05 14:27

    Simply you are missing this:

    <div class="carousel-caption">
    

    Before the <h1>Text 1</h1> So it's like this:

    <div class="carousel-item active">
      <div class="carousel-caption">
        <h1>Text 1</h1>
      </div>
    </div>
    
    0 讨论(0)
  • 2021-01-05 14:29

    You can use display: table; and display: table-cell; display along with vertical-align: middle;

    .carousel-item {
        display: table;
        text-align: center;
    }
    
    .carousel-item h1 {
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }
    

    The key here is vertical-align: middle; which works only if a div is a table.

    Regarding the horizontal alignment, the text-align: center; goes to .carousel-item. I updated my code.

    0 讨论(0)
  • 2021-01-05 14:31

    Change your CSS for h1 into the following:

    .carousel-item h1 {
      position: absolute;
      margin: 0;
      color: white;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    
    0 讨论(0)
  • 2021-01-05 14:41

    You can use the Bootstrap 4 utility classes (no additional CSS is needed)...

    https://www.codeply.com/go/ORkdymGWzM

    <div class="carousel slide" data-ride="carousel">
        <div class="carousel-inner text-center">
            <div class="carousel-item active">
                <div class="d-flex h-100 align-items-center justify-content-center">
                    <h1>Text 1</h1>
                </div>
            </div>
            <div class="carousel-item">
                <div class="d-flex h-100 align-items-center justify-content-center">
                    <h1>Text 2</h1>
                </div>
            </div>
            <div class="carousel-item">
                <div class="d-flex h-100 align-items-center justify-content-center">
                    <h1>Text 3</h1>
                </div>
            </div>
        </div>
    </div>
    
    0 讨论(0)
提交回复
热议问题