Fixed width div on left, fill remaining width div on right

CssCss FloatOverflowFixed WidthVariable Width

Css Problem Overview


I want a div with a fixed width image on the left and a variable width div with a background color, which should extend its width 100% on my device. I can't stop the second div from overflowing my fixed div.

When I add overflow:hidden at the variable width div it just jumps under the photo, on the next row.

How can I fix this the right way (i.e. without hacks or margin-left, since I need to make the site responsive later with media queries and I have to change the image with other resolution images for each device)?

  • beginner web designer trying to tackle the horror of responsive websites -

HTML:

<div class="header"></div>
<div class="header-right"></div>

CSS:

.header{
    float:left;
    background-image: url('img/header.png');
    background-repeat: no-repeat;
    width: 240px;
    height: 100px;
    }

.header-right{
    float:left; 
    overflow:hidden; 
    background-color:#000;
    width: 100%;
    height: 100px;
    }

Css Solutions


Solution 1 - Css

Try removing the float:left and width:100% from .header-right — the right div then behaves as requested.

.header {
  float: left;
  background: #efefef;
  background-repeat: no-repeat;
  width: 240px;
  height: 100px;
}

.header-right {
  overflow: hidden; 
  background-color: #000;
  height: 100px;
}

<div class="header"></div>
<div class="header-right"></div>

Solution 2 - Css

with the use of css grid you can achieve this more easily

  • you need to wrap those divs in a wrapper, lets say parent
  • give .parent display: grid
  • give grid-template-areas in .parent and grid-area in both children
  • no need to use float: left in both children adjust the width of left div using grid-template-columns in .parent

.parent {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: auto 1fr;
  grid-template-areas: "header-left header-right";
}
.header {
    background-image: url(img/header.png);
    background-color: #ebebeb;
    background-repeat: no-repeat;
    height: 100px;
    grid-area: header-left;
}

.header-right {
    overflow: hidden;
    background-color: #000;
    width: 100%;
    height: 100px;
    grid-area: header-right;
}

<div class="parent">
  <div class="header"></div>
  <div class="header-right"></div>
</div>

css has become much more advanced and answering with the help of that advanced css just if it can be useful to someone :)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnamaria MiehsView Question on Stackoverflow
Solution 1 - CsscaitrionaView Answer on Stackoverflow
Solution 2 - CssZuberView Answer on Stackoverflow