Hamreen Ahmad Hamreen Ahmad - 4 months ago 6
HTML Question

CSS properties don’t work for paragraphs with pre elements inside

I have a paragraph that contains a

<pre>
element and some text, like the following:

<p class="par1">
<pre>
this is second paragraph
ok
ok
</pre>
These text are inside the paragraph must be RED
</p>


And I have used the following code to change the background color of the paragraph, but it doesn’t affect the paragraph and I don’t know why.

<style>
.par1{
background-color:red;
color:green;
}
</style>


Here’s the whole code:



<!doctype html>
<html>

<head>
<title>Test id and class attribute</title>
<style>
.par1 {
background-color: red;
color: green;
}
</style>
</head>

<body>
<div class="div1">
Some text
<h1>An important heading</h1>
<p class="par1">
<pre>
this is second paragraph
ok
ok
</pre>
This text is inside the paragraph and it must be red.
</p>
</div>
</body>

</html>





I know that if I use the class of the div
.div1
, it works fine, but I want to know why the first one doesn’t work.

.div1{
background-color:red;
color:green;
}

Answer

as @dippas said, it's about the <pre>-tag inside a <p>-tag

<p>-tags can not contain block-level elements. as <pre> is a block-level element, browsers seem to close the <p>-tag, before the <pre>-tag opens (see your browser inspector). thus the styles on <p> could not be inherited by the <pre>-tag

for a good discussion with helpful hints, see:

<pre> tag making browsers close paragraphs

Comments