简体   繁体   中英

Center Div in Center of Screen

I know it's been asked quite a few times here and on the web, but I'm having a difficulty with this.

I have a single div container in my HTML document. Just a body with a background and a div.

I'm making a "coming soon" page. I want to center the container div to the center of the screen, so it'd work on mobile, desktop and any resolution.

I'm trying different code layouts, but I can't just get it right.

How can I do this?

Link to my code: https://jsbin.com/puyege/edit?html,output

 @import url(http://fonts.googleapis.com/earlyaccess/alefhebrew.css); body { margin: 0 !important; background: url("http://lbscience.org/wp-content/uploads/2016/01/Horsehead-Nebula.jpg"); background-size: cover; background-position: center; background-repeat: no-repeat; background-attachment: fixed; } #container { background-color: green !important; font-family: 'Alef Hebrew', sans-serif; position: fixed; top: 50%; -webkit-transform: translate(0, -50%); -ms-transform: translate(0, -50%); transform: translate(0, -50%); text-align: center; } .bold { font-weight: bold; } #quote { font-size: 2em; } 
 <div id="container"> <p class="bold">"אי-שם, משהו מחכה להתגלות" <p> <p>קארל סייגן-</p> <img alt="logo" id="logo" src="http://lbscience.org/wp-content/uploads/2015/10/LittleBig-Science-Old-Logo-300x90.png" /> <p>בקרוב</p> </div> 

You need to set left: 50% on #container and then adjust your transform to account for this. You also aren't closing <p class="bold"> correctly:

 @import url(http://fonts.googleapis.com/earlyaccess/alefhebrew.css); body { margin: 0 !important; background: url("http://lbscience.org/wp-content/uploads/2016/01/Horsehead-Nebula.jpg"); background-size: cover; background-position: center; background-repeat: no-repeat; background-attachment: fixed; } #container { background-color: green !important; font-family: 'Alef Hebrew', sans-serif; position: fixed; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); transform: translate(-50%, -50%); text-align: center; } .bold { font-weight: bold; } #quote { font-size: 2em; } 
 <div id="container"> <p class="bold">"אי-שם, משהו מחכה להתגלות"</p> <p>קארל סייגן-</p> <img alt="logo" id="logo" src="http://lbscience.org/wp-content/uploads/2015/10/LittleBig-Science-Old-Logo-300x90.png" /> <p>בקרוב</p> </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