space_food_ space_food_ - 8 months ago 23
CSS Question

Creating a 100% width left, fixed width right, centered in container

I am trying to create a simple layout where it is filled width in the left div, with a max-width, and fixed width in the right div.

These divs are centered in a container.

If the max-width of the left div is hit, everything obviously works as intended. However, on a mobile phone, this functionality does not work as intended, and the left div would take up an entire row, forcing the right div onto a second line.

What is the correct way to solve this issue?

Here is the JS fiddle: https://jsfiddle.net/Lozqg9ya/



.container {
margin: auto;
border: 1px solid black;
text-align: center;
display: inline-block;
width: 100%;
}

.right {
width: 50px;
display: inline-block;
border: 1px solid black;
}

.left {
max-width: 1500px;
width: 100%;
display: inline-block;
border: 1px solid black;
}

<div class="container">
<div class="left">
Here we are
</div>
<div class="right">
Yeah
</div>
</div>




Answer Source

You can use calc() on .left:

width: calc(100% - 50px - 8px);

The 100% is the default you wanted; 50px is substracting the .right size. The 8px is some borders, paddings, margins. Hence, I would also add padding: 0; and margin: 0; to your coude.

Full code:

.container
{
  border: 1px solid red;
  text-align: center;
  display:inline-block;
  width: 100%;
  padding: 0;
  margin: 0;
}
.right
{
  width: 50px;
  display: inline-block;
  border: 1px solid green;
  padding: 0;
  margin: 0;
}
.left
{
  max-width: 1500px;
  width: calc(100% - 50px - 8px);
  display: inline-block;
  border: 1px solid black;
  padding: 0;
  margin: 0;
}

If you want to change any padding or magin, do not forget to increase the -8px;