Sunday, April 1, 2018

html - How to style specific child tags in css





I am styling chat layout and got stuck at the point . This is my snippet



https://jsfiddle.net/9ce1d8or/





#chatbox {
background: #f7f7f7;
padding: 10px;
}

#chatbox #chatmessages {
max-height: 400px;
overflow: auto;
}
#chatbox #chatmessages .messages {
margin-bottom: 20px;
}
#chatbox #chatmessages .messages .message {
padding: 10px;
border-radius: 25px;

}
#chatbox #chatmessages .messages .message.message-received {
background: green;
margin: 5px 0;
max-width: 40%;
}
#chatbox #chatmessages .messages .message.message-sent {
float: right;
margin: 5px 0;
background: #ccc;

max-width: 40%;
}

.clearfix::after {
content: '';
display: block;
clear: both;
}






Hello

Hello mrs


Hello mrs

Hello

Hello





Hello

Hello mrs


Hello mrs

Hello

Hello









I want to style every first .message-received which is child of .messages element. Tried all pseudo selectors but nothing worked as expected. I have tried
.messages .message-received::first-of-type, ::nth-of-type(2)
Is the markup style correct for what i want to style? or i am doing wrong with css? Your suggestions will be very helpful.


Answer



The first-child selector (like the name is suggesting) selects the first child of an element - in your case that would be the element of class .product.
There is no first child of class .message-received in your markup, thatswhy that selector doesn't work for your case.




To select the first element of a specific class, you would do a little trick. First style all elements of that class with the first class styles and then revert the styles for all siblings, using the adjacent sibling selector ~:



#chatbox #chatmessages .messages .message-received {
background: red;
}
#chatbox #chatmessages .messages .message-received ~ .message-received {
background: green;
}



This way, the first element of the class will be styled:





#chatbox {
background: #f7f7f7;
padding: 10px;
}


#chatbox #chatmessages {
max-height: 400px;
overflow: auto;
}

#chatbox #chatmessages .messages {
margin-bottom: 20px;
}

#chatbox #chatmessages .messages .message {

padding: 10px;
border-radius: 25px;
}

#chatbox #chatmessages .messages .message.message-received {
background: red;
margin: 5px 0;
max-width: 40%;
}


#chatbox #chatmessages .messages .message.message-sent {
float: right;
margin: 5px 0;
background: #ccc;
max-width: 40%;
}

.clearfix::after {
content: '';
display: block;

clear: both;
}

#chatbox #chatmessages .messages .message-received ~ .message-received {
background: green;
}






Hello

Hello mrs


Hello mrs

Hello

Hello






Hello mrs

Hello


Hello mrs

Hello

Hello









No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...