我正在做一项让我感到悲伤的任务。我应该制作一个与图像颜色相匹配的红色框。此框应该位于页面的中央。该框应该占页面的 80%。图像应该在框内。图片应该是它所在的 BOX 宽度的 80%。图片应该垂直居中。我正在尝试使用 CSS 来做到这一点。这是我的代码。我错过了什么?
HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="box">
<ul>
<li>
<a href="http://blackhawks.nhl.com/">
<img src="http://www.wallpaperpimper.com/wallpaper/Hockey/Chicago_Blackhawks/Chicago-Blackhawks-Blackhawks-Logo-1-JPS6RQXFBC-1024x768.jpg">
</a>
</li>
</ul>
</div>
</body>
</html>
CSS:
.box {
width: 80%;
background-color: #dd111;
margin-left: auto;
margin-right: auto;
}
.box ul {
margin-left:auto;
margin-right:auto;
}
.box ul li {
width: 80%;
vertical-align: middle;
}
最佳答案
如果列表不是必需的,您可以这样做。如果要使用列表,则需要将 ul 填充和边距设置为 0。
<style type="text/css">
.box {
width:80%;
margin:0 auto 0 auto;
}
img {
width:80%;
margin:0 auto 0 auto;
display:block;
}
.box-stripe {
width:80%;
height:15px;
margin:0 auto 0 auto;
}
</style>
<body>
<div class="box">
<div class="box-stripe"></div>
<img src="yourimage.png" alt="" />
<div class="box-stripe"></div>
</div>
</body>
或者如果您更喜欢列表,您可以这样做。无论如何它应该让你接近。
<style type="text/javascript">
.box {
width:80%;
margin:0 auto 0 auto;
}
.box ul {
width:80%;
margin:0 auto 0 auto;
padding:0px;
display:block; /*may not need to do this but I don't think a UL is a block element */
}
.box ul .box-stripe {
width:100%;
display:block;
height:15px;
padding:0px;
margin:0px;
}
.box ul .img {
width:100%;
display:block;
padding:0px;
margin:0px;
}
</style>
<body>
<div class="box">
<ul>
<li>class="box-stripe"></li>
<li class="img"><img src="yourimage.png" alt="" /></li>
<li class="box-stripe"></li>
</ul>
</div>
</body>
每个浏览器在填充、边距、行高等方面都以不同方式对待 HTML 元素。这就是我推荐 CSS 重置的原因。大多数 UL 默认都有一些填充。
关于HTML/CSS 格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8810888/