Say I have the following:
<div style="border: 1px solid black; width:300px;">
<span style="background: red; width:100px;">one</span>
<span style="background: yellow; width:100p开发者_如何转开发x;">two</span>
<span style="background: red; width:100px;">three</span>
</div>
What CSS can I apply to make the spans equally spaced within the div?
I have to strongly disagree with the other answers, suggesting inline-block
and float:left
as these solutions will give you a floating layout. This may be fine most of the time, I have seen cases where 33.33% + 33.33% + 33.33% > 100%, usually on Android devices. This pushes the last cell onto the next line.
Since you are trying to create a tabular appearance, I would recommend using tabular display styles:
<style>
#myTable {
display: table;
border: 1px solid black;
width: 300px;
}
#myTable > * {
display: table-cell;
width: 33.33%;
}
</style>
<div id="myTable">
<span style="background: red">one</span>
<span style="background: yellow">two</span>
<span style="background: red">three</span>
</div>
Spans
are inline elements and have the width of their respective contents. If you want to set a specific width, use block elements like div
or p
and arrange them horizontally with float:left;
<div style="border: 1px solid black; width:300px;">
<div style="float:left; background: red; width:100px;">one</div>
<div style="float:left; background: yellow; width:100px;">two</div>
<div style="float:left; background: red; width:100px;">three</div>
</div>
Generally speaking, span
is used for formatting purposes, like setting font style, etc. Block elements like div
can be used for layout and positioning.
You can tweak spans
to do the same, but it's not recommended. Divs
are there for this exact purpose.
Try adding 'float:left;' style to your span.
In addition to the previous answers, I would strongly advice against using styling inline with your HTML. You should try to keep things separated, and styling belongs in your CSS file/files.
Also, try looking into a grid system, that makes this kind of formatting much easier and maintainable. Good examples are:
http://960.gs/
http://cssgrid.net/
or
http://twitter.github.com/bootstrap/ (a full CSS framework that adds some extra features)
There are several others, just posting these as examples.
span {
display: inline-block;
width: 33.33%;
text-align: center;
}
This should work, removing each 100px width you have in your spans. Spans are by default inline elements, so applying a width property directly to them has no effect. First you have to "blockalize" them. If you have some problem with some browser with the display: inline-block;
, you can use float: left;
instead.
精彩评论