Dynamically calculate position right with calc()

Viewed 345

I have been tasked with styling a banner, however the banner itself is a third party tool with severely limited styling options. It's probably easier if I share an example of what I'm working with and then talk through the limitations and what I'm trying to achieve.

body {
  margin: 0;
}
.main {
  height: 200vh;
  min-height: 250px;
  width: 1200px;
  background: #cdcdcd;
  margin: 0 auto;
  padding: 20px;
}
<div class="main">
  Main website content
</div>

<div class="banner" style="position: fixed; width: 100%; max-width: 600px; height: 80px; background: gray; bottom: 20px; right: 20px; color: white; padding: 20px;">Banner content</div>

Here is a version in Codepen if that's easier.

As you can see, the main website content is centered and is responsive up to (in this case) 1200px, after which the width becomes fixed. The banner needs to always sit at the bottom right, but it should remain within the constraints of the main website content. When the viewport is less than 1200px this solution works fine, the issue I have is of course that on viewports wider than 1200px, the banner breaks out of the constraints of the site.

Generally this wouldn't be an issue, it's easily fixed with calc() and a media query to get the viewport width, but now come the limitations of the banner tool:

  • I can only add inline CSS via the tool to the element banner, there is no wrapper or inner element I can target
  • I cannot add CSS to the site that the banner will appear on
  • I cannot use JavaScript, either on the site or in the banner tool
  • I can't affect the HTML mark-up in any way (e.g. I can't put the banner inside main

Sorry for the long introduction but hopefully that explains my dilemma. My question is this: is it possible, using CSS calc(), to determine when my viewport is above 1200px and to add (half) that amount to my right offset without affecting the offset when the viewport is less than 1200px, or is there just no solution to this?

1 Answers

Here is one idea that rely on the use if min() in order to define the max-width. You make it either 600px (for bigger screen) or 50% (for small screen) and then adjust the position using translate after centring the element:

body {
  margin: 0;
}
.main {
  height: 200vh;
  min-height: 250px;
  width: 1200px;
  background: #cdcdcd;
  margin: 0 auto;
  padding: 20px;
}

* {
  box-sizing:border-box;
}
<div class="main">
  Main website content
</div>

<div class="banner" style="position: fixed; width: 100%; max-width: min(50%,600px); height: 100px; background: gray; bottom: 20px; right: 0;left:0;margin:auto;transform:translate(50%);border:1px solid red; color: white; padding: 20px;">Banner content</div>

The support is still not good (https://caniuse.com/#feat=mdn-css_types_min) but shortly it will be available on Firefox and all the major browser will be covered.

Related