Answer the question
In order to leave comments, you need to log in
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
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;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question