user1283776
user1283776

Reputation: 21764

Center content vertically in Ionic?

I want to be able to center most anything vertically on a screen:

For example

Is this possible to do with some custom css class?

Right now I am using the code below. It works but is not very good as I choose at which percentage the content will start. So I need one of these for every page and if content becomes longer I have to modify the percentage.

.loginForm .scroll {
  height: 100%;
}
.loginForm .loginForm-wrapper {
  position: absolute;
  top: 30%;
  left: 0;
  right: 0;
}

Upvotes: 1

Views: 801

Answers (2)

Andrew Bone
Andrew Bone

Reputation: 7291

You could do something with a little bit of JS, though I think @Jan Unld's answer is sufficient.

calcMiddle = function () {
    var middleObject = document.querySelector('#middle'),
        middleHeight = middleObject.clientHeight / 2,
        middleWindow = window.innerHeight / 2,
        middleMargin = middleWindow - middleHeight;
    middleObject.style.marginTop = middleMargin + "px";
};

calcMiddle();
body {
    margin: 0;
}
#middle {
    padding: 10px;
    background: #abcabc;
}
<body onresize="calcMiddle();">
    <div id="middle">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean a arcu sed neque volutpat lacinia mattis vitae nulla. Mauris in rutrum dui. Nullam nec dui rhoncus diam aliquam molestie. Nullam volutpat odio dignissim lorem ornare luctus. Aenean iaculis lectus venenatis aliquam porttitor. Etiam facilisis libero nec risus blandit aliquam. Donec sed ipsum nibh. Vestibulum sit amet accumsan ipsum. Maecenas viverra auctor orci, et scelerisque enim congue et.</p>
    </div>
</body>

Example:

http://jsfiddle.net/link2twenty/y7h60kr7/

Upvotes: 0

Jan Unld
Jan Unld

Reputation: 370

There are different ways to center content vertically. I'm often using the way to transform them. Let's say you got a container in which another element should be centered.

.container {
  position: relative; /* required */

  height: 150px;
  width: 100px;
  background: #efefef;
  text-align: center;
  border-radius: 4px;
}
.center-me {
  display: block;
  font-family: Consolas;
  font-size: 12px;
  padding: 5px 10px;
  background: #000;
  color: #fff;
  border-radius: 4px;

  position: absolute; /* required */
  top: 50%; /* required */
  left: 50%;
  transform: 
    translateY(-50%) /* required */
    translateX(-50%);
}
<div class="container">
  <div class="center-me">
    center
  </div>
</div>

Upvotes: 1

Related Questions