简体   繁体   中英

How do i center two divs vertically in Javascript?

Here is the code snippet:

var wrapper = document.createElement('DIV');
wrapper.setAttribute("width", x * rows);
wrapper.setAttribute("height", y * columns);
wrapper.align = "center";

var buttonWrap = document.createElement('DIV');
buttonWrap.setAttribute("style", "clear:float");

As you can see in my code snippet, I have tried to center my div. But this code doesn't work. What works is making both divs fixed. But at the end of the day, the second div will then be upon the first div.

Please help.

If you can use only CSS I would do it this way:

 .container { width: 500px; height: 150px; border: solid black 1px; /* Align center */ display: flex; justify-content: center; align-items: center; } .small { background-color: red; width: 100px; height: 30px; } .big { background-color: green; width: 100px; height: 100px; } 
 <div class="container"> <div class="small"></div> <div class="big"></div> </div> 

If you want to do it in javascript , apply the style written above in CSS this way:

var container = document.getElementsByClassName('container')[0];
container.style.display = "flex";

and so on...

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