D
D
Dvorak2015-11-16 00:55:01
css
Dvorak, 2015-11-16 00:55:01

How to align an element vertically?

Wrote a function in jQuery to align vertically to the center. Everything works, but when the browser window is resized, the inscription moves out. Where is the mistake?

function alignCenter(elem) {
  elem.css({
    left: ($(window).width() - elem.width()) / 2 + 'px',
    top: ($(window).height() - elem.height()) / 2 + 'px'
     })
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DmitrySorokin, 2015-11-16
@allishappy

You can add a function to the browser window change event. B call your function inside:
$( window ).resize(function() {
alignCenter();
});
You can also add a small timeout to the function so that it does not work out many times when resizing, but with a delay of 200 -300 milliseconds. - will load the browser less.
But in general, I would advise to solve this with css (you should always try to use css+html as much as possible for styling (your case) and only js as a last resort).
For example, using inline blocks and a pseudo-element:
(source https://css-tricks.com/centering-in-the-unknown/)

/* Родительский блок  */
.block {
  text-align: center;
  white-space: nowrap;
}
 
/* Псевдоэлемент, который занимает всю высоту родителя. Относительно его центра будет выравниваться позиция выравниваемого элемента */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* Выравниваемый элемент с неопределенной шириной и высотой */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

In the same article you can find other ways

R
Rikcon, 2015-11-16
@Rikcon

It's high time to use https://philipwalton.github.io/solved-by-flexbox/
And if you still want it your way, then you need to hang your function on the resize event.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question