CSS calc(); to position a div

Cazineer picture Cazineer · Jan 30, 2017 · Viewed 12.4k times · Source

I'm attempting to create a div that has a width and height of 37% of the view width.

I want the div to be centered in the middle so I attempted to take 50% of the view width and subtract the 37% value.

I then want the div to sit 50% outside of the parent div. It's basically a cover photo with a profile image. The bottom position would need to be negative in order to force the business-cover-logo outside the business-view-wrapper and the only way I could think of was multiply by a negative number.

<div class="business-view-cover">
    <div class="business-cover-logo"></div>
</div>

.business-view-cover {
    position: relative;
    height: calc(100vw * 0.5625);
    background-size: cover;
    background-position: center center;
    background-image: url('../images/business-cover-1.png');

    .business-cover-logo {
        position: absolute;
        --width-profile: calc(100vw * 0.37);
        --half-width: calc(var(--width-profile) / 2);
        --profile-bottom: calc(-1 * var(--half-width));
        bottom: calc(var(--profile-bottom) * -1);
        left: calc(50vw - var(--width-profile));
        width: var(--width-profile);
        height: var(--width-profile);
        border: 4px solid $e1-background-grey;
        border-radius: 1.6rem;
        background-size: cover;
        background-position: center center;
        background-image: url('../images/logo-cover-napa.png');
    }
}

Example of it working with fixed values.

.business-view-cover {
    position: relative;
    height: calc(100vw * 0.5625);
    background-size: cover;
    background-position: center center;
    background-image: url('../images/business-cover-1.png');

    .business-cover-logo {
        position: absolute;
        bottom: -7.65rem;
        left: calc(50vw - 7.65rem);
        width: 15.3rem;
        height: 15.3rem;
        border: 4px solid $e1-background-grey;
        border-radius: 1.6rem;
        background-size: cover;
        background-position: center center;
        background-image: url('../images/logo-cover-napa.png');
    }
}

Answer

Itay Gal picture Itay Gal · Jan 30, 2017

I edited my answer after understanding what you need: To position your logo, use position: relative and set the bottom to a negative value, and in order to center the logo use the left: calc(50% - 100px) where 100px are half of your logo size.

HTML

<div class="cover-photo">
    <div class="logo">
    </div>
</div>

CSS

.cover-photo{
  width: 100%;
  margin: auto;
  border: 1px solid black;
  text-align: center;
}

.logo{
  background-color: navy;
  width: 200px;
  height: 200px;
  position:relative;
  bottom: -100px;
  left: calc(50% - 100px);
}

Example

Also, there are no nesting classes in CSS, you should move .business-cover-logo outside the brackets