Vertically align div to middle of element

2020-04-12 16:12发布

So basically, I want my page to look like this. The logo (green triangle) is "images/logo.png", and the three other boxes are Username input/Password input/Submit button.

enter image description here

The code I have tried does not work - it squashes it all up on the left side of the page.

 <div class="login-box">
            <div class="row">
                <div class="col-sm-2">
                    <img src="{{ asset('images/logo.png') }}" />
                </div>
                <div class="col-sm-10">
                    <p align="center">{{ form_widget(form.username, {'attr': {'class': 'form-control', 'placeholder': 'authentication.username'|trans } }) }}</p>
                    <p align="center">{{ form_widget(form.password, {'attr': {'class': 'form-control', 'placeholder': 'authentication.password'|trans } }) }}</p>
                    <p align="center">{{ form_widget(form.log_in, {'attr': {'class': 'btn btn-lg btn-primary btn-block'}, 'label': 'authentication.log.in'|trans }) }}</p>
                </div>
            </div>
        </div>

<style>
    .login-box {
        width: 800px;
        vertical-align: middle;
    }
</style>

What am I doing wrong?

Thanks

3条回答
Ridiculous、
2楼-- · 2020-04-12 16:25

You might consider using the col-sm-offset to change the position of your image and your fields. Try:

<div class="col-sm-2 col-sm-offset-4">
     <img src="{{ asset('images/logo.png') }}" />
</div>
<div class="col-sm-5 col-sm-offset-6">

Play with "col-sm-offset-x" until you get it positioned correctly.

查看更多
Evening l夕情丶
3楼-- · 2020-04-12 16:31

I have created a example demo with some dummy data but you will get the idea how to achieve it

.col-sm-2, .col-sm-10 {
min-height: 100vh;
display: flex;
align-items : center;
}
查看更多
Evening l夕情丶
4楼-- · 2020-04-12 16:35

Let's assume your parent element is 100% height and width of the viewport.

You can easily vertically align any element, if you don't mind using the transform property, with a few lines of code.

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

You can throw in a margin: 0 auto; if you want to horizontally align it as well (and it is a block type element).

Fiddle Here

To apply it to your code:

  • Make sure the parent of login-box is the element with 100% height and width.
  • Apply the above styles to the login-box class.
查看更多
登录 后发表回答