-1

I want to create divs that stand side by side with and each one fill 25% of the screen in height and width. My script creates divs with 25% height and width, but they stay one below the other. My script is:

   function createDiv() {
     var div_created = document.createElement("div");
     div_created.setAttribute("class", "div1");

     document.body.appendChild(div_created);
   }
.div1 {
  width: 50%;
  height: 50%;
  background-color: #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="estilo_segundo.css">
<body>
<button onclick="createDiv()">Click</button>
</body>
Sumit patel
  • 3,807
  • 9
  • 34
  • 61
Isaac Meneses
  • 163
  • 1
  • 12

3 Answers3

2
.div1 {
  width: 50%;
  height: 50%;
  background-color: #000000;
  float:left;
}
0

Add html,body style & inside div1 add float:left;

 html,body
 {
    width: 100%;
    height: 100%;
 }

.div1 {
  width: 50%;
  height: 50%;
  background-color: #000000;
  float:left;
}

Live Demo Here

Snippet Example

function createDiv() {
  var div_created = document.createElement("div");
  div_created.setAttribute("class", "div1");
  document.body.append(div_created);
}
html,
body {
  width: 100%;
  height: 100%;
}
.div1 {
  width: 50%;
  height: 50%;
  background-color: #000000;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <button onclick="createDiv()">Click</button>
</body>
Sumit patel
  • 3,807
  • 9
  • 34
  • 61
0

You could use the display: table; in a wrapper div and simplify your JS:

<html><head>
<script type="text/javascript">
function createDiv() {
    document.getElementById('div1').innerHTML += '<div></div>';
}
</script>
<style type="text/css">
#div1 {
    width: 100%;
    height: 100%;
    display: table;
    background-color: #000000;
}
#div1 div {
    display: table-cell;
    border: 1px solid green; /* green for display */
}
</style>
</head><body>
<button onclick="createDiv()">Click</button>
<div id="div1" name="div1"></div>
</body></html>

This adds an inner 'cell' to the div1 wrapper div. Since the wrapper takes up the display height/width, each inner div has an 'auto' width to it (as a table <td> would).

txtechhelp
  • 6,625
  • 1
  • 30
  • 39