如何使Javascript创建的DIV居中?

时间:2017-08-18 20:11:09

标签: javascript html css

这是我的计数器代码(从www.w3schools.com代码修改)。

我正在努力将输出水平居中。我试图用DIV包装,然后使用以下技术来集中DIV,但没有成功,任何指针都赞赏:

  1. 使用CSS使用text-align: center;
  2. 为外部DIV设置样式
  3. 使用CSS通过margin-left: auto;&来设置外部DIV的样式margin-right:auto;
  4. 使用Javascript水平对齐设置输出的margin属性;
  5. <!DOCTYPE HTML>
    <html>
    <head>
        <style>
            .bigger {
                text-align: center;
                font-size: 1.35em;
            }
            .counter_p {
                text-align: center;
                font-size: 6em;
                padding: 0px 0px 0px 0px;
                line-height: 1em;
            }
            .counter_label {
                font-size: 0.2em;
                line-height: 1em;
            }
    
            }
        </style>
    </head>
    <body>
        <div class="counter_p" id="counter"></div>
        <script>
            function pad(str, max) {
                return str.length < max ? pad("0" + str, max) : str;
            }
    
            // Set the date we're counting down to
            var countDownDate = new Date("Sep 1, 2017 15:37:25").getTime();
    
            // Update the count down every 1 second
            var x = setInterval(function() {
    
                // Get todays date and time
                var now = new Date().getTime();
    
                // Find the distance between now an the count down date
                var distance = countDownDate - now;
    
                // Time calculations for days, hours, minutes and seconds
                var days = pad(String(Math.floor(distance / (1000 * 60 * 60 * 24))),2);
                var hours = pad(String(Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))),2);
    
                var minutes = pad(String(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))),2);
                var seconds = pad(String(Math.floor((distance % (1000 * 60)) / 1000)),2);
    
    
                // My attempt at horizontally centering the output
                document.getElementById('counter').style.margin = '0 auto';
    
                // Output the result in an element with id="counter"
                document.getElementById("counter").innerHTML =
                    "<div style='text-align:center'>"
                    +   "<table border='0'>"
                    +       "<tr>"
                    +           "<td>"
                    +               "<div>"+ days + "</div>"
                    +               "<div class='counter_label'>Days</div>"
                    +           "</td>"
                    +           "<td class='bigger'>|</td>"
                    +           "<td>"
                    +               "<div>" + hours + "</div>"
                    +               "<div class='counter_label'>Hours</div>"
                    +           "</td>"
                    +           "<td class='bigger'>|</td>"
                    +           "<td>"
                    +               "<div>" + minutes + "</div>"
                    +               "<div class='counter_label' >Mins</div>"
                    +           "</td>"
                    +           "<td class='bigger'>|</td>"
                    +           "<td>"
                    +               "<div>" + seconds + "</div>"
                    +               "<div class='counter_label'>Secs</div>"
                    +           "</td>"
                    +           "<td>"
                    +       "</tr>"
                    +   "</table>"
                    +"</div>";
    
    
                // If the count down is over, write some text
                if (distance < 0) {
                    clearInterval(x);
                    document.getElementById("counter").innerHTML = "Countdown is complete";
                }
            }, 1000);
        </script>
    </body>
    </html>
    

3 个答案:

答案 0 :(得分:0)

下面的

是使用JS查找div中心的步骤。最好将它附加到窗口调整大小事件上。因此它会随着用户更改窗口大小而移动。

//create div via js

var div = document.createElement("div");
document.body.appendChild(div);

//find widow width

var winWidth = document.documentElement.clientWidth; 

//find div width 

var divWidth = div.offsetWidth;

//find center position 

var centerPos = (winWidth/2) - (divWidth/2)

//put div at position 

div.style.marginLeft = centerPos+'px';
div {
  height: 100px; 
  width: 100px; 
  background-color: red;
}

答案 1 :(得分:0)

创建容器div来保存倒计时文本在这种情况下有效(使用CSS flexbox,其中justify-content设置为“center”) - flexbox在窗口调整大小时正常工作:

<!DOCTYPE HTML>
    <html>
    <head>
    <style>


    .bigger {
      text-align: center;
      font-size: 1.35em;
    }
    .counter_p {
      text-align: center;
      font-size: 6em;
      padding:0px 0px 0px 0px;
      line-height:1em;

    }
    .counter_label {
        font-size:0.2em;
        line-height:1em;
    }
    .container {
      display: flex;
      justify-content: center;
    }

    }
    </style>
    </head>
    <body>
    <div class="container">
        <div class="counter_p" id="counter"></div>
    </div>
    <script>

      function pad (str, max) {
          return str.length < max ? pad("0" + str, max) : str;
        }

    // Set the date we're counting down to
    var countDownDate = new Date("Sep 1, 2017 15:37:25").getTime();

    // Update the count down every 1 second
    var x = setInterval(function() {

        // Get todays date and time
        var now = new Date().getTime();

        // Find the distance between now an the count down date
        var distance = countDownDate - now;

        // Time calculations for days, hours, minutes and seconds
        var days = pad(String(Math.floor(distance / (1000 * 60 * 60 * 24))),2);
        var hours = pad(String(Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))),2);

        var minutes = pad(String(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))),2);
        var seconds = pad(String(Math.floor((distance % (1000 * 60)) / 1000)),2);

        // Output the result in an element with id="counter"

    document.getElementById("counter").innerHTML = "<div style='text-align:center'><table border='0'><tr><td><div>"+ days + "</div><div  class='counter_label' >Days</div></td><td class='bigger'>|</td><td><div>" + hours + "</div><div class='counter_label'>Hours</div></td><td class='bigger'>|</td><td><div>"
        + minutes + "</div><div class='counter_label' >Mins</div></td><td class='bigger'>|</td><td><div>" + seconds + "</div><div class='counter_label'>Secs</div></td><td></tr></table></div>";



        // If the count down is over, write some text 
        if (distance < 0) {
            clearInterval(x);

    document.getElementById("counter").innerHTML = "Countdown is complete";
        }
    }, 1000);
    </script>

    </body>
    </html> 

注意:旧版浏览器不支持CSS Flexbox,请参阅CSS Flexible Box Layout Module

答案 2 :(得分:0)

您的问题只是以css为中心的常见问题。我建议你熟悉这个概念,因为在编写Web界面时会有很多。

这是关于这个主题的一些话题:

我还邀请您查找YouTube视频:

我的解决方案

使用一个中心(相当于你的第二个想法)

public View getView(int position, View convertView, ViewGroup parent){

        ViewHolder holder;

        if (convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.list_view_scan, parent, false);
            holder = new ViewHolder();
            holder.scanView = (ImageView) convertView.findViewById(R.id.view_scan);
            holder.frameLayout = (FrameLayout) convertView.findViewById(R.id.zoomLayout);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }

        // Then do operation here on your view holder
        // ...

        return convertView;

}

.centered { display: table; margin: 0 auto; } 仅在您将div作为宽度或显示表格时才有效。

margin: 0 auto;
          function pad (str, max) {
              return str.length < max ? pad("0" + str, max) : str;
            }

        // Set the date we're counting down to
        var countDownDate = new Date("Sep 1, 2017 15:37:25").getTime();

        // Update the count down every 1 second
        var x = setInterval(function() {

            // Get todays date and time
            var now = new Date().getTime();

            // Find the distance between now an the count down date
            var distance = countDownDate - now;

            // Time calculations for days, hours, minutes and seconds
            var days = pad(String(Math.floor(distance / (1000 * 60 * 60 * 24))),2);
            var hours = pad(String(Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))),2);

           var minutes = pad(String(Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60))),2);
            var seconds = pad(String(Math.floor((distance % (1000 * 60)) / 1000)),2);


        // My attempt at horizontally centering the output

        document.getElementById('counter').style.margin = '0 auto';

            // Output the result in an element with id="counter"

        document.getElementById("counter").innerHTML = "<div class='centered'><table border='0'><tr><td><div>"+ days + "</div><div  class='counter_label' >Days</div></td><td class='bigger'>|</td><td><div>" + hours + "</div><div class='counter_label'>Hours</div></td><td class='bigger'>|</td><td><div>"
            + minutes + "</div><div class='counter_label' >Mins</div></td><td class='bigger'>|</td><td><div>" + seconds + "</div><div class='counter_label'>Secs</div></td><td></tr></table></div>";



            // If the count down is over, write some text 
            if (distance < 0) {
                clearInterval(x);

        document.getElementById("counter").innerHTML = "Countdown is complete";
            }
        }, 1000);
#counter{
  border: 3px solid red;
}

.bigger {
  text-align: center;
  font-size: 1.35em;
}

.counter_p {
  text-align: center;
  font-size: 6em;
  padding:0px 0px 0px 0px;
  line-height:1em;
}

.counter_label {
  font-size:0.2em;
  line-height:1em;
}

.centered {
  border: 3px solid blue;
  display: table;
  margin: 0 auto;
}