1

Is it valid CSS to have a block element inside of an inline element?

For example:

<a href="#">
    <span></span>
</a>

Is span { display: block; } illegal while the <a> is inline?

4

2 回答 2

5

CSS rules do not, in any way, influence the validity of markup.

The rules for how to handle display: block elements inside display: inline elements can be found in the CSS specification.

When an inline box contains an in-flow block-level box, the inline box (and its inline ancestors within the same line box) are broken around the block-level box (and any block-level siblings that are consecutive or separated only by collapsible whitespace and/or out-of-flow elements), splitting the inline box into two boxes (even if either side is empty), one on each side of the block-level box(es). The line boxes before the break and after the break are enclosed in anonymous block boxes, and the block-level box becomes a sibling of those anonymous boxes. When such an inline box is affected by relative positioning, any resulting translation also affects the block-level box contained in the inline box.

于 2013-06-09T21:43:48.017 回答
2

Here is a visual approach in addition to Quentin's answer.

JSFiddle

enter image description here

CSS:

h1 {
    font-size: 16px;
}

div { 
    border: 1px solid black;
    padding: 8px; margin: 12px; 
    background-color: #ccc; 
    width: 70% 
}

.test1 { 
    display: inline; 
    height: 25px;
    border: 1px solid red;
    background-color: white; 
}

.test2 { 
    display: block; 
    height: 25px;
    border: 1px solid red;
    background-color: white; 
}

.test3 {
    display: inline-block; 
    height: 25px;
    border: 1px solid red;
    background-color: white;
}
于 2013-06-09T21:53:20.380 回答