简体   繁体   中英

How to keep div in center-height when I resize the browser window?

I am trying to center in height a div, however it does not work when I resize the browser screen.

How to edit this to achieve the adjustable margin-top on resize?

Thank you

<script>    
var h = $(window).height();
var parentHeight = h;   
var childHeight = $('#a-middle').height();      
$('#a-middle').css('margin-top', (parentHeight - childHeight) /2);
</script>

The answer should be in js since flexbox won't work on IE-9 答案应该是js,因为flexbox不能在IE-9上运行

you should stick to a CSS solution though, there are several way to achive this

.alignVertical {
    position:relative;
    display:inline-block;
    top:50%;
    transform:translateY(-50%);
}

jsfiddle: https://jsfiddle.net/jorjmt70/

or using flexbox

.parent {
    display:flex;
    height:100vh;
    background-color:red;
    justify-content:center;
    align-items:center;
    flex-direction:column;
}

jsfiddle: https://jsfiddle.net/mdh9h876/

if you want to use flex box use autoprefixer to get deeper browsersupport: https://github.com/postcss/autoprefixer

Although you can easily do this with pure CSS, your bounty stated that you want a JS answer.

If you are interested in a pure CSS answer, see this answer that has multiple different methods on how to center elements vertically/horizontally.


You could simplify your jQuery to the following:

$('#a-middle').css('margin-top', function () {
    return ($(window).height() - $(this).height()) / 2
});

Then you could just place this within a resize event listener and chain the .resize() method in order to trigger the event initially when the browser loads.

Example Here

$(window).on('resize', function () {
    $('#a-middle').css('margin-top', function () {
        return ($(window).height() - $(this).height()) / 2
    });
}).resize();

JavaScript equivalent (without jQuery):

Example Here

var verticalCentering = function () {
    var el = document.querySelector('#a-middle');
    el.style.marginTop = (window.innerHeight - el.offsetHeight) / 2 + 'px';
}
window.addEventListener('resize', verticalCentering);
verticalCentering();

For a div called 'center-me':

$(document).ready(centerDiv);
$(window).resize(centerDiv);

function centerDiv() {
    var winHeight = $(document).innerHeight(),
        divHeight = $('.center-me').height();

    $('.center-me').css('marginTop', (winHeight - divHeight) / 2 );
}

You need to call it when the document is ready, to get it centered in the first place, then on resize-event, to keep it centered.

Here is the fiddle for it: Fiddle

To make a div always stay at the center of the screen, the properties you could use are top and left attributes after setting the position attribute to absolute. However you will need to set these properties dynamically when the browser is resized. This can be done using the JQuery method - resize().

/*css code*/
.div{
   position:absolute;
   top:100px;
   left:50px;
   background:black;
}

/*JS Code*/
function keep_div_centered()
{
     window_height = $(window).height();
     window_width = $(window).width();
     obj_height = $('.keepincenter').height();
     obj_width = $('.keepincenter').width();
     $('.keepincenter').css('top',(window_height/2)-(obj_height/2)).css('left',(window_width/2)-(obj_width/2))
}
keep_div_centered();
$(window).resize(function(){
     keep_div_centered();
})

/* HTML Code */
<div class="keepincenter"></div>

Link to the fiddle - http://jsfiddle.net/y0937t06/

A CSS solution could do the trick for you.

 div.center { height: 100px; width: 300px; top: 50%; left: 50%; margin-top: -50px; margin-left: -150px; position: absolute; background-color: red; } 
 <div class="center">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div> 

This CSS code work fine in IE8+, Firefox and Chrome.

But you must know the sizes of the DIV that you want to adjust correctly. If the height and width are dynamic, you just have to update the style accordingly with JavaScript. Don't forget to apply the class center in JS on need to your DIV.

Explanations :

  • margin-top : - height / 2 because top : 50% only centered vertically the top of the DIV.
  • margin-left : - width / 2 because left : 50% only centered horizontally the left of the DIV.
  • position : absolute so that the DIV can center over all the page.

This can be achieved using simple CSS with deep browser support back to IE8 .

 html, body { height: 100%; } .parent { display: table; table-layout: fixed; width: 100%; height: 100%; } .child { display: table-cell; vertical-align: middle; text-align: center; background: red; } 
 <div class="parent"> <div class="child">This is always centered.</div> </div> 

Using table-layout makes it simple: the child can be vertically aligned (top, middle, bottom) and will take up all the available height. You're not resorting to JavaScript, CSS with patchy support or having to hard-code any figures, it should just work.

Depending on the specifics of what you're looking to do, flexbox or - as a last resort - JavaScript might be required, but for most cases display: table-cell is your friend.

That said, if it's acceptable for older browsers to get a different layout, just use @Victor's answer: this is what flexbox is for.

$(window).resize(function () {
var h = $(document).height();
var parentHeight = h;
var childHeight = $('#imagegallery').height();
$('#imagegallery').css('margin-top', (parentHeight - childHeight) / 2);
            });

For me, this is the holy grail of CSS :) The most reliable method I found is setting the container element as follows:

display: -webkit-flex;
-webkit-justify-content: center; /* horizontal */
-webkit-align-items: center; /* vertical */

It is simple and has no prerequisites on any other CSS properties.

The fiddle below places content 30px above vertical center:

 #container { width: 500px; height: 300px; background-color: red; display: -webkit-flex; -webkit-justify-content: center; -webkit-align-items: center; } #content { background-color: green; margin-bottom: 30px; } 
 <div id="container"> <span id="content">Content</span> </div> 

Handle window_resize event of the current window and try putting above code there.

It should give you expectd functionality.

This approach is very useful when you want to center both vertically and horizontally an absolute position div. It work also on IE8

You need to set the both outer and inner divs as

position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin:auto;  

margin:auto it's fundamental to center divs in this case.

You could also set the height and width of the .in div and still you would see it centered vertically and centered also when you resize the browser.

* {
    margin: 0;
    padding: 0;
}
html, body {
    position: relative;
    height: 100%;
    width: 100%;
}
.in, .out {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;  
}
.in {
    background-color: red;
    height: 50%;
    width:50%;
 }
.out {
    background-color: blue;
}

EXAMPLE 1 JSFIDDLE height, width: in percentages: http://jsfiddle.net/a_incarnati/1o5zzcgh/3/

EXAMPLE 2 - JSFIDDLE fixed height, fixed width http://jsfiddle.net/a_incarnati/1o5zzcgh/4/

Give display: table-cell; to the parent and align the contents vertically using vertical-align and give the padding to adjust the necessary spacing from top.

.child{
    display:table-cell;
    vertical-align:top;
    padding-top: 50px;
}

This will keep the margin uniform throughout.

use css

first give a height to your element.

#a-middle {
    height: 20px;
    position: fixed;
    top: calc(50% - 10px);
    left: 0;
}

or use js

$(function(){
    $('#a-middle').each(function(){
        var t = $(window).height()/2 - $(this).outerHeight()/2;
        $(this).css({top: t + "px"});
    });
});
$(window).resize(function(){
    $('#a-middle').each(function(){
        var t = $(window).height()/2 - $(this).outerHeight()/2;
        $(this).css({top: t + "px"});
    });
});

The problem with the previous solutions is that you won't be able to center the div, if he's larger than the available vertical size.

If you want your div to take 50% of the page you can use the CSS vertical height based unit:

.mydiv {
   height: 50vh;
   top: 50%;
   left: 50%;
   position: fixed;
   width: 50vh;
   margin-top: -25vh;
   margin-left:-25vh;
   border: solid black 1px;
}

So your DIV will not only be centered but also maintain its ratio.

Play with margin-left and margin-top of that div, using the width and height of the window and div.

$(function () {
    makeDivCenter();
    $(window).resize(function () {
        makeDivCenter();
    });
});



function makeDivCenter() {
   var windowWidth = $(window).width();
   var divWidth = $(".center").width();
   var windowHeight = $(window).height();
   var divHeight = $(".center").height();

   $(".center").css({
      'margin-left': (windowWidth / 2) - (divWidth / 2) + "px",
      'margin-top': (windowHeight / 2) - (divHeight / 2) + "px"
   });
}

Here is jsfiddle for your reference https://jsfiddle.net/fnuud7g6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM