CSS ID variations
Hey, I am guessing that this is probably fairly trivial, but I am having difficulty finding an answer or figuring it out nonetheless.
I'm trying to create a grid of colored squares with arbitrary spacing between them. This in itself is easy to do, especially because I need only nine squares. But while I look at my completed code, I cannot help but feel there is a far more simple and efficient wa开发者_Python百科y to accomplish this.
At the moment, I have nine different IDs declared in my css, one for each square.
div.container{
position:relative;
left:50px;
top:50px;
background-color:rgb(45,45,45);
height:300px;
width:300px;
}
#square{
position:absolute;
background-color:rgb(52,82,222);
left:20px;
top:20px;
height:80px
width:80px
#square2{
position:absolute;
background-color:rgb(58,82,22);
left:110px;
top:20px;
height:80px;
width:80px;
etc etc etc
What I would like to do is find a more efficient way to do this.
Thanks for the help!
You can use a class for the squares that share a property:
.square {
position: absolute;
width: 80px;
height: 80px;
}
Is there a specific reason you're absolutely positioning them though? Sounds like a job better suited for floats.
div.container {
width: 240px;
}
.square {
float: left;
width: 80px;
height: 80px;
}
Assuming that the inner squares are div
s, there are no other div
s inside your container, and each inner div
should be the same width
and height
, this is what I'd do:
.container {
position: relative;
left: 50px;
top: 50px;
background: rgb(45,45,45);
height: 300px;
width: 300px;
}
.container > div {
position: absolute;
background-color: rgb(52,82,222);
height: 80px;
width: 80px;
}
#square1 {
left: 20px;
top: 20px;
}
#square2 {
left: 110px;
top: 20px;
}
..
If you need separate top
and left
properties for each div
, then you have no choice but to use id
s.
You can avoid having to add a class
thanks to using .container > div
, which selects all div
elements that are direct children of .container
.
The HTML would look like this:
<div class="container">
<div id="square1"></div>
<div id="square2"></div>
..
</div>
Why not give all of the squares the same class and apply something like
.square
{
display: inline-block;
width: 80px;
height: 80px;
zoom: 1;
*display: inline /* for IE */
}
That should make all of the blocks wrap nicely without having to add styles for each individual.
精彩评论