Reputation: 19
When I useclass="top-menu"
and class="pull-right"
these two together I get the result is the image is pull-right but the background color does not change to black, What is wrong with my code?
If I delete the class="pull-right"
the background color becomes black
.top-menu {
background-color: black;
}
.pull-right {
float: right;
}
<header>
<div class="header-top">
<div class="container-fluid top-menu">
<img src="..." alt="Awsome_Ticket_Logo" class="pull-right">
</div>
</div>
</header>
Upvotes: 1
Views: 59
Reputation: 2826
I see a lot of developers has this problem with their code. Normally, This issue comes with bad styling of your page structure. Also, the first solution that many developers come with is to use clear: both;
styling in pseudo. But, I think if you learn how to style like a good developer you will never need to use clear
. Just start to write your page in a normal and standard way.
When you give a float
to the child of a parent which doesn't have a float
property, The parent will lose its height (if its the only child of that parent). The best way to avoid this happening its to divide the sections of your page and give them a good floating. This way you'll never need to use clear
styling.
header,
.header-top,
.top-menu {
width: 100%;
float: left;
}
.top-menu {
padding: 5px;
background-color: red;
}
img{
width: 100px;
height: 100px;
display: block;
float: left;
background: blue;
}
<header>
<div class="header-top">
<div class="container-fluid top-menu">
<img src="" alt="Awsome_Ticket_Logo" class="pull-right">
</div>
</div>
</header>
Upvotes: 0
Reputation: 11318
When you float something, it is no longer part of its parent's bounding box. Since there is nothing else in your top-menu
parent, the bounding box will be considered empty and it will have a height of 0.
A common solution to this is to add a clearfix to the parent. This will make it include whatever space was taken up by its floated children:
.top-menu {
background-color: black;
}
.pull-right{
float: right;
}
.top-menu:after {
content: "";
clear: right;
display: table;
}
<header>
<div class="header-top">
<div class="container-fluid top-menu">
<img src="https://via.placeholder.com/150" alt="Awsome_Ticket_Logo" class="pull-right">
</div>
</div>
</header>
Upvotes: 3
Reputation: 423
That's because when things float the container becomes empty, you can use a clearfix: https://jsfiddle.net/wwWaldi/nrysp61w/18/
.clearfix::after {
content: "";
clear: both;
display: table;
}
Upvotes: 0