user2953119
user2953119

Reputation:

Why doesn't my div inside a span work properly?

I'm writing the following HTML markup:

<span> Some Text
    <div id="ch">татата</div>
</span>

and styles:

span{
    border: 1px solid black;
    text-align:center;
    width: 300px;
    height: 300px;
    background: aqua;
}
#ch{
    width:100px;
    height:100px
    background: yellow;   
}

jsFiddle

  1. Why is the height property not applied to a div element which inside the span, but width is applied?
  2. Why is the right border of my span is missing?

Upvotes: 15

Views: 43033

Answers (7)

Vishnu Vardhan
Vishnu Vardhan

Reputation: 21

By default div's is a block element and span is an inline element. Block elements always flow vertically and inline elements always flow next to each other from top left to the bottom right depends on screen width. We can use inline elements under the block element, not vice versa. If we override we expect to see some issues like this on responsive layout.

Upvotes: 2

Piyush Patel
Piyush Patel

Reputation: 1751

First answer: You forgot the semi-colon after height style, that's why it is not rendered.

Second answer: If you look closely, the border appears after the div. This is because you are inserting block level element inside inline element. So, block level element takes it to the next line and then it takes the whole line. On the very next line you can see the right border for the span.

It is bad practice to put block level element inside inline element. In fact, I do not see any practical use of this kind of structure. Please, correct it if you are learning.

Upvotes: 2

NoobEditor
NoobEditor

Reputation: 15871

Your markup is incorrect ( plus missing semi-colon as quoted by Steini, mentioning this for sake of completeness of answer )

Answer 1 : span is an inline element, so having a div inside span is a bad idea, also, it would be better, if you nest span inside span and give inner span display:block property!

Answer 2 : add display:block to span to change the default behavior

working fiddle with correct markup

fiddle with the layout you wanted

Upvotes: 32

Steini
Steini

Reputation: 2783

Because you are missing a semicolon after height: 100px <- this ; is missing in you css file

Upvotes: 2

saman khademi
saman khademi

Reputation: 842

span display:inline you must set it display:inline-block
but this not standard you must use div span always use for text your fiddle demo

Upvotes: 2

christian.s
christian.s

Reputation: 447

span is an inline-element, while div ist not. you should consider swapping them..

Upvotes: 0

Pete
Pete

Reputation: 58422

span is an inline element so it will not take notice of your height and width. For this you need to give it either:

display:block; or display: inline-block

Upvotes: 1

Related Questions