简体   繁体   中英

How do I keep a div center when browser window goes smaller than div size?

Essentially when the browser window goes larger thh div stays centered and creates white space on the outside. I want the same thing to happen when the browser window goes smaller. I want to see less of the div but keep it centered. At the moment I see less of the div but the left side locks so I end up only seeing a slither of the left part of the image (instead of the center). Sorry if this is a convoluted way of asking I am new to programming. Any help would be massively appreciated! Thanks in advance! :)

ps I am also struggling to have the video playing if anyone can help with that too

Here is my code currently

 body { font-family: 'Noto Sans', sans-serif; margin: 0; padding: 0; } #page-container { width: 1920px; margin: auto; }
 <div id="page-container"> <video id="backgroundvid" width="auto" autoplay> <source src="assets/video/portalAnimLowRes.mp4" type="video/mp4"> </video> </div>

You can try

#page-container {
    width:1920px;
    margin-left: -960px;
    position: relative;
    left: 50%;
}        

You can put the pageContainer on absolute position as follows.

#page-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 1920px;
}

Do you really want the horizontal scroll bar?

If you don't, I prefer not to define the width(especially in pixel), as the width of every device varies.

Instead, you can define width as width:100% or width:100vw , this helps to fit the div according to the screen size.

You can try this code:

body {
  font-family: 'Noto Sans', sans-serif;
  margin: 0 auto;
  padding: 0;
}
#page-container {
  width: 100%;
  margin: auto;
}

What about use flexbox?

 body { font-family: 'Noto Sans', sans-serif; margin: 0; padding: 0; } #page-container { width: 1920px; display: flex; align-items: center; justify-content: center; }
 <div id="page-container"> <img src="https://placeimg.com/640/480/any"> </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