vertical-align with Bootstrap 3

I'm using Twitter Bootstrap 3, and I have problems when I want to align vertically two div, for example — JSFiddle link:

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div class="row">
  <div class="col-xs-5">
    <div style="height:5em;border:1px solid #000">Big</div>
  </div>
  <div class="col-xs-5">
    <div style="height:3em;border:1px solid #F00">Small</div>
  </div>
</div>

The grid system in Bootstrap uses float: left, not display:inline-block, so the property vertical-align doesn't work. I tried using margin-top to fix it, but I think this is not a good solution for the responsive design.

</div>

转载于:https://stackoverflow.com/questions/20547819/vertical-align-with-bootstrap-3

csdnceshi54
hurriedly% So you want them to be vertically aligned to the middle, relative to each other, or, in other words, to have the same horizontal axis?
2 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 .row{display: flex; align-items: center;}
3 年多之前 回复
weixin_41568127
?yb? In Bootstrap 4, vertical center align is very different: stackoverflow.com/a/41464397/171456
3 年多之前 回复
csdnceshi76
斗士狗 no one of the answer works perfectly on chrome IE8 and mobile for me with a row containing 5 col- ( and 3 col- on mobile )
大约 4 年之前 回复
csdnceshi74
7*4 IMPORTANT: Both columns need the "vcenter" class. Otherwise it won't work. Spent hour an hour now just figuring that out.
接近 5 年之前 回复
csdnceshi64
游.程 possible duplicate of How to use vertical align in bootstrap
大约 6 年之前 回复
weixin_41568184
叼花硬汉 no no, I want to align vertically the 2 div, no the text inside, something like this jsfiddle.net/corinem/Aj9H9 but in this example I not use bootstrap
接近 7 年之前 回复

23个回答

This answer presents a hack, but I would highly recommend you to use flexbox (as stated in @Haschem answer), since it's now supported everywhere.

Demos link:
- Bootstrap 3
- Bootstrap 4 alpha 6

You still can use a custom class when you need it:

.vcenter {
    display: inline-block;
    vertical-align: middle;
    float: none;
}
<div class="row">
    <div class="col-xs-5 col-md-3 col-lg-1 vcenter">
        <div style="height:10em;border:1px solid #000">Big</div>
    </div><!--
    --><div class="col-xs-5 col-md-7 col-lg-9 vcenter">
        <div style="height:3em;border:1px solid #F00">Small</div>
    </div>
</div>

Bootply

Using inline-block adds extra space between blocks if you let a real space in your code (like ...</div> </div>...). This extra space breaks our grid if column sizes add up to 12:

<div class="row">
    <div class="col-xs-6 col-md-4 col-lg-2 vcenter">
        <div style="height:10em;border:1px solid #000">Big</div>
    </div>
    <div class="col-xs-6 col-md-8 col-lg-10 vcenter">
        <div style="height:3em;border:1px solid #F00">Small</div>
    </div>
</div>

Here, we've got extra spaces between <div class="[...] col-lg-2"> and <div class="[...] col-lg-10"> (a carriage return and 2 tabs/8 spaces). And so...

Enter image description here

Let's kick this extra space!!

<div class="row">
    <div class="col-xs-6 col-md-4 col-lg-2 vcenter">
        <div style="height:10em;border:1px solid #000">Big</div>
    </div><!--
    --><div class="col-xs-6 col-md-8 col-lg-10 vcenter">
        <div style="height:3em;border:1px solid #F00">Small</div>
    </div>
</div>

Enter image description here

Notice the seemingly useless comments <!-- ... -->? They are important -- without them, the whitespace between the <div> elements will take up space in the layout, breaking the grid system.

Note: the Bootply has been updated

</div>

Flexible box layout

With the advent of the CSS Flexible Box, many of web designers' nightmares1 have been resolved. One of the most hacky ones, the vertical alignment. Now it is possible even in unknown heights.

"Two decades of layout hacks are coming to an end. Maybe not tomorrow, but soon, and for the rest of our lives."

— CSS Legendary Eric Meyer at W3Conf 2013

Flexible Box (or in short, Flexbox), is a new layout system that is specifically designed for layout purposes. The specification states:

Flex layout is superficially similar to block layout. It lacks many of the more complex text- or document-centric properties that can be used in block layout, such as floats and columns. In return it gains simple and powerful tools for distributing space and aligning content in ways that webapps and complex web pages often need.

How can it help in this case? Well, let's see.


Vertical aligned columns

Using Twitter Bootstrap we have .rows having some .col-*s. All we need to do is to display the desired .row2 as a flex container box and then align all its flex items (the columns) vertically by align-items property.

EXAMPLE HERE (Please read the comments with care)

<div class="container">
    <div class="row vertical-align"> <!--
                    ^--  Additional class -->
        <div class="col-xs-6"> ... </div>
        <div class="col-xs-6"> ... </div>
    </div>
</div>
.vertical-align {
    display: flex;
    align-items: center;
}

The Output

Vertical aligned columns in Twitter Bootstrap

Colored area displays the padding-box of columns.

Clarifying on align-items: center

8.3 Cross-axis Alignment: the align-items property

Flex items can be aligned in the cross axis of the current line of the flex container, similar to justify-content but in the perpendicular direction. align-items sets the default alignment for all of the flex container’s items, including anonymous flex items.

align-items: center; By center value, the flex item’s margin box is centered in the cross axis within the line.


Big Alert

Important note #1: Twitter Bootstrap doesn't specify the width of columns in extra small devices unless you give one of .col-xs-# classes to the columns.

Therefore in this particular demo, I have used .col-xs-* classes in order for columns to be displayed properly in mobile mode, because it specifies the width of the column explicitly.

But alternatively you could switch off the Flexbox layout simply by changing display: flex; to display: block; in specific screen sizes. For instance:

/* Extra small devices (767px and down) */
@media (max-width: 767px) {
    .row.vertical-align {
        display: block; /* Turn off the flexible box layout */
    }
}

Or you could specify .vertical-align only on specific screen sizes like so:

/* Small devices (tablets, 768px and up) */
@media (min-width: 768px) {
    .row.vertical-align {
        display: flex;
        align-items: center;
    }
}

In that case, I'd go with @KevinNelson's approach.

Important note #2: Vendor prefixes omitted due to brevity. Flexbox syntax has been changed during the time. The new written syntax won't work on older versions of web browsers (but not that old as Internet Explorer 9! Flexbox is supported on Internet Explorer 10 and later).

This means you should also use vendor-prefixed properties like display: -webkit-box and so on in production mode.

If you click on "Toggle Compiled View" in the Demo, you'll see the prefixed version of CSS declarations (thanks to Autoprefixer).


Full-height columns with vertical aligned contents

As you see in the previous demo, columns (the flex items) are no longer as high as their container (the flex container box. i.e. the .row element).

This is because of using center value for align-items property. The default value is stretch so that the items can fill the entire height of the parent element.

In order to fix that, you can add display: flex; to the columns as well:

EXAMPLE HERE (Again, mind the comments)

.vertical-align {
  display: flex;
  flex-direction: row;
}

.vertical-align > [class^="col-"],
.vertical-align > [class*=" col-"] {
  display: flex;
  align-items: center;     /* Align the flex-items vertically */
  justify-content: center; /* Optional, to align inner flex-items
                              horizontally within the column  */
}

The Output

Full-height columns with vertical aligned contents in Twitter Bootstrap

Colored area displays the padding-box of columns.

Last, but not least, notice that the demos and code snippets here are meant to give you a different idea, to provide a modern approach to achieve the goal. Please mind the "Big Alert" section if you are going to use this approach in real world websites or applications.


For further reading including browser support, these resources would be useful:


1. Vertically align an image inside a div with responsive height2. It's better to use an additional class in order not to alter Twitter Bootstrap's default .row.

csdnceshi71
Memor.の Awesome! It works great also on Drupal Bootstrap
接近 3 年之前 回复
weixin_41568127
?yb? , salam,1 soal dashtam,age betonid konakam konid mamnon misham.manzor az You must have a total score of 1000 in at least 200 non-community wiki answers to achieve this badge. chie?be chesoal haie non-community wiki migan.khaheshan javab bede.harchi serch kardam motavajeh nashodam.Email:eh.taghdisi@gmail.com
大约 3 年之前 回复
csdnceshi62
csdnceshi62 Great response for Bootstrap 3. Note that Bootstrap 4 has flexbox functionality built in.
3 年多之前 回复
weixin_41568196
撒拉嘿哟木头 …or one could add flex-wrap: wrap to stop the float model from breaking.
接近 4 年之前 回复
weixin_41568131
10.24 Thanks for the great solution, it worked for me, you made my day!
大约 4 年之前 回复
csdnceshi54
hurriedly% works great for aligning the tricky menu items with a search box, just need to make sure to wrap both in a row and define the styles written by OP
4 年多之前 回复
csdnceshi76
斗士狗 People are complaining that the default ( col-xs-* etc) bootstrap functionality doesn't work with this answer. You are customizing what you want, but at the same time trying to depend on the BS defaults? Define your own classes for your layouts appropriately and use the power of bootstrap to it's full extent. (i.e. always AT LEAST define both -xs- and -md- where you will be doing anything even mildly interesting, this will override the defaults). This example worked perfectly for where and how I needed it (within my bootstrap).
4 年多之前 回复
weixin_41568134
MAO-EYE This answer should be the best answer for modern browsers.
4 年多之前 回复
csdnceshi59
ℙℕℤℝ queries over flexboxes is what exactly I have mentioned. I just didn't create a demo for the second section: full-height columns... as I prefer not to repeat myself. Thank you.
4 年多之前 回复
csdnceshi69
YaoRaoLov The problem still remains that this isn't a Bootstrap friendly solution because it breaks the responsive grid (columns no longer stack). A workaround is to use a @media query like this: codeply.com/go/iJQNo8ynfT
4 年多之前 回复
csdnceshi78
程序go "Complaining about the mobile-first thing". (Almost) the solely purpose of Bootstrap is this "mobile-first thing". I couldn't find any use case when one would use Bootstrap grid system if it weren't due to making a responsive (mobile-adaptative) site. If you simply want some sort of "columns" in a desktop site then you don't need all to overhead Bootstrap provides; that's old, plain and simple HTML+CSS. So if someone is providing "solutions" for vertical align in Bootstrap columns without providing the "mobile fallback" at the same time, then someone is missing the point here.
4 年多之前 回复
csdnceshi59
ℙℕℤℝ has mentioned. It's a good choice to declare the flexbox settings between specific breakpoints. Say -xs- in global scope, -sm- for 768 <= width and so on. Please let me know what you think.
4 年多之前 回复
csdnceshi70
笑故挽风 and everyone else complaining about the mobile-first thing... it's easy to fix by just providing a mobile fallback see example 2 with mobile fallback. Also, it can easily be used with all bootstrap. Here's a complex example with panels, thumbnails, etc or see my explaination here.
4 年多之前 回复
csdnceshi52
妄徒之命 HAML version: .row{style: 'display: flex; align-items: center;'}
4 年多之前 回复
csdnceshi56
lrony* That's actually one of the answers that I'd like upvote more than once. Well done.
大约 5 年之前 回复
csdnceshi78
程序go Qolami still cannot find any use case for your suggestions. One of Bootstrap's core, disctintive features is that columns stack on top of each other once they don't fit horizontally. That doesn't happen anymore with your solution. The grid system works even if you load just the styles, as you can see in this fiddle. No js; just css. Change size of the rendering area and it will respond. That doesn't happen in any of your examples. The "mobile first" approach is lost, making Bootstrap unnecessary. So this answer it's incorrect, misleading or incomplete.
5 年多之前 回复
csdnceshi59
ℙℕℤℝ queries. Thanks for your attention anyway.
5 年多之前 回复
csdnceshi78
程序go also, in the fiddle you provided as a supposed "working example" in your reply to my comment, if you open the js console you will notice the following error message: Uncaught Error: Bootstrap's JavaScript requires jQuery. Bootstrap is loaded, but jQuery is a dependency and it isn't. In case of further doubts, you can test for the "existance" of Bootstrap with some of the methods explained here: stackoverflow.com/questions/13933000/…
5 年多之前 回复
csdnceshi78
程序go sorry but you are wrong. Bootstrap css is loaded in every case, but bootstrap itself is not running. In your first and second Codepens it's trivial to demonstrate the examples are not running as simply as by changing your col-*to fit 12 columns in every screen size, as I told you in my previous comment (did you try it??). Then make your browser small enough and notice they don't stack: codepen.io/anon/pen/pvLpeR codepen.io/anon/pen/zxWpzR Also there are no traces of bootstrap .js in the sources - check it by yourself.
5 年多之前 回复
csdnceshi59
ℙℕℤℝ I'm not sure what you mean. All the demos in this answer include Twitter Bootstrap. It can be seen through External Resources section in the fiddles, and the CSS settings in CodePen demos. Of course twitter bootstrap doesn't use Flexible box layout, but it doesn't mean this answer is incompatible with Twitter Bootstrap. If you doubt that twitter bootstrap is embedded, just do an inspect element on each column.
5 年多之前 回复
csdnceshi78
程序go although you are using classes named col-*, your fiddle/codepens are not making use of bootstrap, so they are misleading. Your examples don't work with bootstrap; its grid system is not based on flex, thus they are incompatible. Simply try whatever of your examples in a bootstrap-powered page and you'll realize they don't work.
5 年多之前 回复
csdnceshi59
ℙℕℤℝ I couldn't reproduce the problem, this is working for me just fine. Please consider providing an online example to demonstrate the issue in action.
5 年多之前 回复
csdnceshi78
程序go I tried this and wasn't working for me the expected way, until I edited your fiddles and realized that this is totally unuseful and a waste of time. Doing this misses completely the point of responsive design, as columns won't stack anymore one on top of the others when they don't fit into the screen, thus rendering the need for bootstrap totally unuseful and rendering your site unresponsive. To see what I mean, change any col-xs-* to col-xs-12 in the respective examples, make your browser screen very small (like a mobile device) and see the results: no more responsiveness.
5 年多之前 回复
csdnceshi59
ℙℕℤℝ I've added the link in my previous comment, here you are: flexiejs.com
接近 6 年之前 回复
csdnceshi59
ℙℕℤℝ Flexible box layout is not supported in IE9 and olders. There is a workaround, though.
接近 6 年之前 回复
csdnceshi67
bug^君 This is actually the best solution and should have more support. And of course we, developers, must use it as much as we can to propagate it.
大约 6 年之前 回复
csdnceshi55
~Onlooker This is beautiful! Thanks for answering with the de facto solution for the years to come.
大约 6 年之前 回复
csdnceshi79
python小菜 After a little research, I actually found that HTML5Please.com says that there is enough support to use it. So that s pretty awesome! html5please.com/#flexbox
大约 6 年之前 回复
csdnceshi79
python小菜 I love using Flex and I've been using it with a Chrome Packaged App which means I don't have to worry about cross-browser css, however on other projects I can't use it yet because it isn't supported in older browsers. Just thought that would be helpful info.
大约 6 年之前 回复

The below code worked for me:

.vertical-align {
    display: flex;
    align-items: center;
}
csdnceshi63
elliott.david Anyone got a solution that works with a single column? I got a row, and then inside just a col-md-6. This solution and the rest of the flexbox ones only work when there are 2 columns
接近 3 年之前 回复
csdnceshi74
7*4 Simplest solution IMHO
3 年多之前 回复

I genuinely find the following code works using Chrome and not other browsers than the currently selected answer:

.v-center {
    display:table!important; height:125px;
}

.v-center div[class*='col-'] {
   display: table-cell!important;
   vertical-align:middle;
   float:none;
}
.v-center img {
   max-height:125px;
}

Bootply Link

You may need to amend the heights (specifically on .v-center) and remove/change div on div[class*='col-'] for your needs.

If you are using the Less version of Bootstrap, and compiling into CSS yourself, you can use some utility classes to use with Bootstrap classes.

I've found these to work fantastically well where I want to preserve the responsiveness and configurability of the Bootstrap grid system (like using -md or -sm), but I want all columns in a given row to all have the same vertical height (so that I can then vertically align their content and have all columns in the row share a common middle).

CSS/Less:

.display-table {
    display: table;
    width: 100%;
}
.col-md-table-cell {
    @media (min-width: @screen-md-min) {
        display: table-cell;
        vertical-align: top;
        float: none;
    }
}
.col-sm-table-cell {
    @media (min-width: @screen-sm-min) {
        display: table-cell;
        vertical-align: top;
        float: none;
    }
}
.vertical-align-middle {
    vertical-align: middle;
}

HTML:

<div class="row display-table">
    <div class="col-sm-5 col-sm-table-cell vertical-align-middle">
        ...
    </div>
    <div class="col-sm-5 col-sm-table-cell vertical-align-middle">
        ...
    </div>
</div>

I thought I'd share my "solution" in case it helps anyone else who isn't familiar with the @media queries themselves.

Thanks to @HashemQolami's answer, I built some media queries that would work mobile-up like the col-* classes so that I could stack the col-* for mobile but display them vertically-aligned in the center for larger screens, e.g.

<div class='row row-sm-flex-center'>
    <div class='col-xs-12 col-sm-6'></div>
    <div class='col-xs-12 col-sm-6'></div>
</div>

.

.row-xs-flex-center {
    display:flex;
    align-items:center;
}
@media ( min-width:768px ) {
    .row-sm-flex-center {
        display:flex;
        align-items:center;
    }
}
@media ( min-width: 992px ) {
    .row-md-flex-center {
        display:flex;
        align-items:center;
    }
}
@media ( min-width: 1200px ) {
    .row-lg-flex-center {
        display:flex;
        align-items:center;
    }
}

More complicated layouts that require a different number of columns per screen resolution (e.g. 2 rows for -xs, 3 for -sm, and 4 for -md, etc.) would need some more advanced finagling, but for a simple page with -xs stacked and -sm and larger in rows, this works fine.

csdnceshi80
胖鸭 I should have analyzed your html code more thoroughly. :) I do use the .row modifier aswell though but in my case (wordpress), it has been changed in the parent theme which ultimately led me adding the clear: both; again.
3 年多之前 回复
csdnceshi78
程序go Sorry for the confusion...In BS3 fashion, as you can see in my HTML example, I use that as a .row modifier...so it should look like class="row row-sm-flex-center". The BS3 .row definition handles the clear:both;
3 年多之前 回复
csdnceshi80
胖鸭 In my case I had to add a clear: both; to the classes inside the media queries in order to get this to work.
3 年多之前 回复

Try this in the CSS of the div:

display: table-cell;
vertical-align: middle;
csdnceshi54
hurriedly% parent element needs to be display:table
3 年多之前 回复
csdnceshi78
程序go It makes it really tricky to switch to responsive mode.
4 年多之前 回复

Update 2018

I know the original question was for Bootstrap 3, but now that Bootstrap 4 has been released, here is some updated guidance on vertical center.

Important! Vertical center is relative to the height of the parent

If the parent of the element your trying to center has no defined height, none of the vertical centering solutions will work!

Bootstrap 4

Now that BS4 is flexbox by default there are many different approaches to vertical alignment using: auto-margins, flexbox utils, or the display utils along with vertical align utils. At first "vertical align utils" seems obvious but these only work with inline and table display elements. Here are some Bootstrap 4 vertical centering options..


1 - Vertical Center Using Auto Margins:

Another way to vertically center is to use my-auto. This will center the element within it's container. For example, h-100 makes the row full height, and my-auto will vertically center the col-sm-12 column.

<div class="row h-100">
    <div class="col-sm-12 my-auto">
        <div class="card card-block w-25">Card</div>
    </div>
</div>

BS4 - Vertical center using auto-margins Demo

my-auto represents margins on the vertical y-axis and is equivalent to:

margin-top: auto;
margin-bottom: auto;

2 - Vertical Center with Flexbox:

vertical center grid columns

Since Bootstrap 4 .row is now display:flex you can simply use align-self-center on any column to vertically center it...

       <div class="row">
           <div class="col-6 align-self-center">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

or, use align-items-center on the entire .row to vertically center align all col-* in the row...

       <div class="row align-items-center">
           <div class="col-6">
                <div class="card card-block">
                 Center
                </div>
           </div>
           <div class="col-6">
                <div class="card card-inverse card-danger">
                    Taller
                </div>
          </div>
    </div>

BS4 - Vertical center different height columns Demo


3 - Vertical Center Using Display Utils:

Bootstrap 4 has display utils that can be used for display:table, display:table-cell, display:inline, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.

<div class="row h-50">
    <div class="col-sm-12 h-100 d-table">
        <div class="card card-block d-table-cell align-middle">
            I am centered vertically
        </div>
    </div>
</div>

BS4 - Vertical center using display utils Demo

Also see: Vertical Align Center in Bootstrap 4


Bootstrap 3

Flexbox method on the container of the item(s) to center:

.display-flex-center {
    display:flex;
    align-items:center;
}

Transform translateY method:

.transform-center-parent {
    position: relative;
    transform-style: preserve-3d;
}

.transform-center {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

Display inline method:

.display-inline-block {
    display:inline;
}
.display-inline-block > div {
    display:inline-block;
    float:none;
    vertical-align: middle;
}

Demo of Bootstrap 3 centering methods

csdnceshi71
Memor.の Here is the Bootstrap documentation for mx-auto (horizontal centering), thus it makes sense that my-auto centers vertically (y-axis).
3 年多之前 回复

I just did this and it does what I want it to do.

.align-middle {
  margin-top: 25%;
  margin-bottom: 25%;
}

And now my page looks like

<div class='container-fluid align-middle'>
    content

 ----------------------------------
 |                                |
 |   --------------------------   |
 |  |                          |  |
 |  |                          |  |
 |  |                          |  |
 |  |                          |  |
 |  |                          |  |
 |   --------------------------   |
 |                                |
 ----------------------------------
csdnceshi56
lrony* The problem with this approach is that it doesn't seem to work when the DIV has a height specified: jsfiddle.net/4bpxen25/1 I'd recommend: stackoverflow.com/a/28519318/1477388
接近 4 年之前 回复

I ran into this same issue. In my case I did not know the height of the outer container, but this is how I fixed it:

First set the height for your html and body elements so that they are 100%. This is important! Without this, the html and body elements will simply inherit the height of their children.

html, body {
   height: 100%;
}

Then I had an outer container class with:

.container {
  display: table;
  width: 100%;
  height: 100%; /* For at least Firefox */
  min-height: 100%;
}

And lastly the inner container with class:

.inner-container {
  display: table-cell;
  vertical-align: middle;
}

HTML is as simple as:

<body>
   <div class="container">
     <div class="inner-container">
        <p>Vertically Aligned</p>
     </div>
   </div>
</body>

This is all you need to vertically align contents. Check it out in fiddle:

Jsfiddle

共23条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐