简体   繁体   中英

How to center focused element?

The code below focuses on second element using javascript however the focused element sticks to bottom of page. I want to have focused element in the center of page how to do that?

 $(function(){ $("#two").focus(); }); 
 body{color:white;} #fis{height:600px;width: 60px;background-color:red;} #two{height:50px;width: 60px;background-color:green;} #thr{height:600px;width: 60px;background-color:blue;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fis">hello </div> <div id='two' tabindex='1'>mr </div> <div id='thr'>john </div> 

You can use JS to select the focused element and then scroll the window to it :

$('html, body').stop().animate({
    scrollTop: $(element_focused).offset().top
}, 300);

With a little math you can calculate the center of the element focused and change the scrollTop value.

Add margin:0 auto; left/right margins to auto to center the element horizontally:

 $(function(){ $("#two").focus().addClass('getCentered'); }); 
 body{color:white;} #fis{height:600px;width: 60px;background-color:red;} #two{height:50px;width: 60px;background-color:green;} #thr{height:600px;width: 60px;background-color:blue;} .getCentered{margin:0 auto;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fis">hello </div> <div id='two' tabindex='1'>mr </div> <div id='thr'>john </div> 

And if you want it always available in the center of the screen horizontally and vertically even with scroll, you can use fixed position with some calculations. check the snippet below center calculation with css:

 $(function(){ $("#two").focus().addClass('getCentered'); }); 
 body{color:white;} #fis{height:600px;width: 60px;background-color:red;} #two{height:50px;width: 60px;background-color:green;} #thr{height:600px;width: 60px;background-color:blue;} .getCentered{position:fixed; left:50%; top:50%; margin:-25px 0 0 -30px;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fis">hello </div> <div id='two' tabindex='1'>mr </div> <div id='thr'>john </div> 

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