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?

d-_-b
  • 21,536
  • 40
  • 150
  • 256
faressoft
  • 19,053
  • 44
  • 104
  • 146

2 Answers2

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
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;
}
Eric Hotinger
  • 8,957
  • 5
  • 36
  • 43