为什么文本在列表项中不对齐?
问题描述:
给定以下简单的页面,其示出了一个无序列表:为什么文本在列表项中不对齐?
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Day Picker</title>
<style>
* { margin: 0; }
html, body { height: 100%; }
.unordered-list
{
height: 100%;
margin: 0 auto;
width: 75%;
text-align: center;
list-style-type: none;
}
.unordered-list li
{
background: red;
float: left;
height: 33%;
}
</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function initializeUnorderedList(unorderedList)
{
// initialize layout
var items = unorderedList.querySelectorAll("li");
var blockIndices = [];
$(items).each(function(index, element)
{
if ($(element).hasClass("block"))
blockIndices.push(index);
});
blockIndices.push(items.length);
for (var i = 0, j = 0; i < blockIndices.length - 1; ++i)
{
var width = 100/(blockIndices[i + 1] - blockIndices[i]);
do {
$(items.item(j)).css("width", width + "%");
} while (++j < blockIndices[i + 1]);
}
}
var unorderedLists = document.querySelectorAll(".unordered-list");
for (var i = 0; i < unorderedLists.length; ++i)
initializeUnorderedList(unorderedLists.item(i));
});
</script>
</head>
<body>
<ul class="unordered-list">
<li class="block">first row, first column</li>
<li class="block">second row, first column</li>
<li>second row, second column</li>
<li class="block">third row, first column</li>
<li>third row, second column</li>
<li>third row, third column</li>
<li>third row, fourth column</li>
<li>third row, fifth column</li>
<li>third row, sixth column</li>
<li>third row, seventh column</li>
</ul>
</body>
</html>
文本的<li>
元件内部应居中(垂直和水平)。
编辑: 固定不良标记
答
似乎集中在下面的例子:
虽然它可能不工作取决于您的浏览器,你的商标的有效性通常,HTML不喜欢<ul>
内的<div>
元素。
建议的解决方案:
使用与哪一行,你想指定的指标,如“1
”,“2
”和‘3
’,让使用Javascript/jQuery的处理您的宽度的情况。
HTML:
<ul class="unordered-list">
<li class='1'>first row, first column</li>
<li class='2'>second row, first column</li>
<li class='2'>second row, second column</li>
<li class='3'>third row, first column</li>
<li class='3'>third row, second column</li>
<li class='3'>third row, third column</li>
<li class='3'>third row, fourth column</li>
<li class='3'>third row, fifth column</li>
<li class='3'>third row, sixth column</li>
<li class='3'>third row, seventh column</li>
</ul>
的jQuery:
//This will group each of your classes and apply the %-based width.
$('.1,.2,.3').each(function(){
var width = Math.floor(100/($('.' + $(this).attr('class')).length));
$(this).css('width',width + '%');
});
的jQuery(企图垂直定心):
$('.1,.2,.3').each(function(){
var width = Math.floor(100/($('.' + $(this).attr('class')).length));
var height = $(this).height()/2;
$(this).css('width',width + '%')
.css('margin-top',height + 'px')
.css('height',($(this).height() - height) + 'px');
});
应该有一个'ul'或'ol'内比'li'以外的元素。包装列表的'div'元素使这个无效的HTML标记。 –
@DavidThomas - +1谢谢 - 修正了糟糕的标记。 – 0xbadf00d