Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a block level <span> element inside a <p> element

I know that <p> is to be used specifically with inline elements. But what if you change an inline element like <span> into a block-level element using { display:block } and contain it within a <p>?

ie.

<html>
<head>
<style>

  p {
    background: red;
    height: 100px;
    width: 100px;
    }

  p span {
    display: block;
    background: blue;
    height: 50px;
    width: 50px;
    }

</style>
</head>

<body>

<p>
  <span>I am a pizza</span>
</p>

</body>
</html>

Is that just wrong in every sense of the word? I know it is not common (ie. most would question why I didn't just use a div) but it's a hypothetical situation. It passes validation tests, but is it sloppy as all heck/bad practice? Would you scoff if you read that code?

like image 758
Tammy Gasser Avatar asked Mar 23 '23 08:03

Tammy Gasser


1 Answers

A span element is always a text/inline/phrase element in HTML, and the HTML syntax rules that restrict p element content to such elements relate to HTML only. So they are not affected by CSS settings that may make a span a block element in the CSS (rendering) sense.

In CSS, you can assign any defined value to the display property, no matter what the element is like. CSS is ignorant of the meanings of elements as defined in HTML or other markup language specifications.

Thus, there is no formal objection.

Whether it is good style, or otherwise acceptable, is more complicated. There does not seem to be any statement on this in specifications, but it is reasonable to say that you should not change basic rendering features elements in vain. For example, in normal conditions, you should not use span and then say display: block in CSS, when there is the more logical approach of using div. One reason to this principle is that it keeps your document in a better shape in non-CSS rendering situations or when all or some of your style sheet is not applied.

On the other hand, you would not change display in vain if you have a text paragraph and you wish to render part of its content as a block, e.g. as a centered or indented line, possibly with a background color that stretches through the available width. You cannot use div inside p, so the more natural markup is not available.

Since the example is not a real one, it is impossible to say whether it is OK to deploy this approach in your case.

like image 139
Jukka K. Korpela Avatar answered Mar 31 '23 14:03

Jukka K. Korpela