我有一个内联 JS 元素(倒计时器),我需要将其居中。但是当我使用 text-align:center 和 width:100% 时,它会拉伸(stretch)到整个页面,每个页面之间有 25% 的空间,而不是实际的中心。
我实际需要它居中的方式是这样的:http://prnt.sc/b8v9fv (左侧和右侧的空间相等)。知道我应该注意什么来解决这个问题吗?
https://jsfiddle.net/gnj8nLre/
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>onepageskiw</title>
<link href="styles.css" rel="stylesheet" type="text/css">
<script src="js.js"></script>
</head>
<body>
<div id="forsidediv">
<img id="forsidepic" src="forsidepic.png">
</div>
<div id="overskrift">
<h1>EVENTET STARTER OM</h1>
</div>
<div id="countdowner">
<table id="table">
<tr>
<div id="countdown">
<td id="id1"></td>
<td id="id2"></td>
<td id="id3"></td>
<td id="id4"></td>
</div>
<tr>
<tr>
<td class="timeLabel">Days</td>
<td class="timeLabel">Hours</td>
<td class="timeLabel">Mins</td>
<td class="timeLabel">Secs</td>
</tr>
</tr>
</tr>
</table>
</div>
<script>
CountDownTimer('06/25/2016 10:00 AM', 'id');
function CountDownTimer(dt, id)
{
var end = new Date(dt);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById(id+"1").innerHTML = days;
document.getElementById(id+"2").innerHTML = hours;
document.getElementById(id+"3").innerHTML = minutes;
document.getElementById(id+"4").innerHTML = seconds;
}
timer = setInterval(showRemaining, 1000);
}
</script>
</body>
</html>
CSS:
@charset "utf-8";
body {
margin:0;
}
h1 {
position:absolute;
width:100%;
text-align:center;
margin:0;
color:black;
font-family:Helvetica;
}
#countdowner {
color:black;
position:absolute;
margin:0;
margin-top:1em;
padding:0;
width:100%;
font-size:2em;
font-family:Helvetica;
}
#table {
width:100%;
text-align:center;
}
#forsidediv {
position:fixed;
text-align: center;
bottom:0;
}
#forsidepic {
width: 100%;
}
最佳答案
您应该删除width:100%;
来自#table
并添加margin:0 auto;
然后向 tds 添加一些填充
#table {
margin:0 auto;
text-align:center;
}
#table td{
padding:0 10px;
}
关于javascript - Div 未正确居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37472103/