2

The question is in the title. How I can center a media horizontal?

My media:

<div class="container">
    <div class="row">
        <div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
            <div class="media">
                <img class="mr-3" src="{{ $user->avatar }}" alt="Avatar">
                <div class="media-body">
                    <h5 class="mt-0">Trexon</h5>
                    <p>LOL</p>
                </div>
            </div>
        </div>
    </div>
</div>

The {{ $user->avatar }} is from Laravel.

enter image description here

Daniel
  • 10,641
  • 12
  • 47
  • 85
Trexon
  • 35
  • 6

2 Answers2

2

You can make the column a flexbox and set its justify-content: center;.

<div class="container">
    <div class="row">
        <div class="col-12 d-flex flex-row justify-content-center">
            <div class="media">
                <img class="mr-3" src="{{ $user->avatar }}" alt="Avatar">
                <div class="media-body">
                    <h5 class="mt-0">Trexon</h5>
                    <p>LOL</p>
                </div>
            </div>
        </div>
    </div>
</div>

Note: You don't need to specify all breakpoints' version of col-12. You only need the smallest one, if all are taking up 12 columns.

David Liang
  • 20,385
  • 6
  • 44
  • 70
  • Thanks! It worked. One question. Do I need a row if I use only one `col`? _Note: You don't need to specify all breakpoints' version of col-12. You only need the smallest one, if all are taking up 12 columns._ **Aight** – Trexon Aug 06 '18 at 19:37
  • @Trexon: nope. You even don't need the `row` as well as `col-12` class if you intend to put up a `
    ` that ALWAYS takes up all available width of the container. You only need the `row` and different versions of `col-12` if you intend to change the width based on breakpoints. But `row` and `col-*` classes have to be used together - whenever there is a row, there must be columns.
    – David Liang Aug 06 '18 at 19:41
  • Aight. Thank You! :) And im gonna learn flexbox! :D – Trexon Aug 06 '18 at 19:47
  • @Trexon: this is a good start: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ – David Liang Aug 06 '18 at 19:51
0
<div class="container">
    <div class="row">
        <div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
            <div class="media justify-content-center">
                <img class="mr-3" src="{{ $user->avatar }}" alt="Avatar">
                <div class="media-body">
                    <h5 class="mt-0">Trexon</h5>
                    <p>LOL</p>
                </div>
            </div>
        </div>
    </div>
</div>

Try this adding the class justify-content-center, if it doesnot work add the class text-center. if it does not work then use flexbox. learn-flex-box

Kiran Bhattarai
  • 175
  • 1
  • 12