简体   繁体   中英

Vertically and horizontally centering HTML5 Javascript

So I have this and want to center it vertically and horizontally:

<div id="hd_hype_container" style="position:relative;overflow:hidden;width:600px;height:405px;">
    <script type="text/javascript" charset="utf-8" src="hd/hd.js?88618"></script>
</div>

I have tried every solution and none seem to work for me. Do I need to add something into the js?

I'd appreciate any help.

Thanks.

Try:

#hd_type_container {
    position: absolute;
    top: 50%;
    height: 50%;
    width: whatever;
    height: whatever; 
    margin-left: -whatever_width_is / 2;
    margin-top: -whatever_height_is / 2;
}

Remember though that absolute or relatively positioned elements are positioned relative to the "closest" parent container that's also absolute or relatively positioned.

In other words, if your div is a child of some other div that's absolutely positioned, you won't be centering to the screen, but centering to the parent div .

Update: Assuming you are trying to make a popup box of some kind, you might also want an overflow: hidden directive too.

<div id="hd_hype_container" style="margin-top:50%;margin:0 auto;width:600px;height:405px;">
    <script type="text/javascript" charset="utf-8" src="hd/hd.js?88618"></script>
</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