InfoHeap
Tech tutorials, tips, tools and more
Navigation
  • Home
  • Tutorials
    • CSS tutorials & examples
    • CSS properties
    • Javascript cookbook
    • Linux/Unix Command Line
    • Mac
    • PHP
      • PHP functions online
      • PHP regex
    • WordPress
  • Online Tools
    • Text utilities
    • Online Lint Tools
search
  • Home
  • > Tutorials
  • > CSS cookbook

How to display a div in browser window center

By admin on Dec 31, 2015

To display a div in browser window center we can use css position value fixed. The left and top value of fixed position are relative to visible window. Here is sample code and rendered screenshot for it.
div-position-fixed-window-center

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<style type="text/css" media="screen">
.center {
  position:fixed;
  background:green;
  width:200px;
  height:50px;
  left:50%;
  top:50%;
  margin-left:-100px;
  margin-top:-25px
}
</style>

Hello world
<div class="center">div in window center</div>
refresh done
try it online

Few points to note

  1. We are using margin-left and margin-top negative value. mergin-left is negative half of div width and margin-top is negative half of div height.
  2. Alternatively we can use left and top css property and use calc function as shown below:

    left:calc(50% - 100px);
    top:calc(50% - 25px);
    

    Note the space before and after minus (-). calc may not work in old IE browsers though.

Suggested posts:

  1. CSS calc function for numeric values
  2. Javascript – catch errors using window.onerror
  3. How to display text on image using css
  4. How to display auto fade out message using jQuery
  5. CSS – place a div in bottom right corner of browser
  6. jQuery – make a div stick at top on scroll
  7. CSS – align div in center horizontally
  8. CSS margin area of a box
Share this article: share on facebook share on linkedin tweet this submit to reddit
Posted in Tutorials | Tagged CSS, CSS cookbook, HTML, Tutorials, Web Development

Follow InfoHeap

facebook
twitter
googleplus
  • Browse site
  • Article Topics
  • Article archives
  • Recent Articles
  • Contact Us
  • Omoney
Popular Topics: AngularJS | Apache | AWS and EC2 | Bash shell scripting | Chrome developer tools | CSS | CSS cookbook | CSS properties | CSS Pseudo Classes | CSS selectors | CSS3 | CSS3 flexbox | Devops | Git | HTML | HTML5 | Java | Javascript | Javascript cookbook | Javascript DOM | jQuery | Linux | Linux/Unix Command Line | Mac | Mac Command Line | Mysql | Networking | Node.js | Online Tools | PHP | PHP cookbook | PHP Regex | Python | Python array | Python cookbook | SEO | Site Performance | SSH | Ubuntu Linux | Web Development | Webmaster | Wordpress | Wordpress customization | Wordpress How To | Wordpress Mysql Queries

Copyright © 2021 InfoHeap.

Powered by WordPress