问题描述:

Here's part of a design:

As you can see - its simply a button that is exactly positioned between the two divs. The code is simply:

 <div class="uc-apply-widget1">

<div class="top">

</div>

<div class="bottom">

<a>Get Started</a>

</div>

</div>

.uc-apply-widget1

{

.top

{

background-color:@primary-color;

height:30rem;

}

.bottom

{

background-color:@primary-600;

padding:0 1.6rem 1.6rem 1.6rem;

a

{

margin-top:-2.8rem;

}

}

}

However, I've come across a problem with using negative margins. I expected to just be able to move the button outside of the bottom div by applying a half height negative margin. Although the button does move upwards, it doesn't move the full 2.8 rem - the amount of movement is the same even if I apply 50rem.

The other solution is to use position relative, which does move the button up, but does not drag the bottom div upwards with it.

So I'm looking to move the button up by n amount and reduce the bottom div height by n amount - any ideas - I may just be having a bad day.

网友答案:

use

position: absolute;
top: 0; left: 0;
transform: translateY(-50%);

on your button

https://developer.mozilla.org/en-US/docs/Web/CSS/transform

网友答案:

Here is one way of realizing your design.

Set the a element to have display: table and position: absolute with top and left offsets to 0 and 50% respectively.

The display: table rule will give you a shrink-to-fit width, which may be what you need.

You can then use the CSS3 transform property to translate the element by -50% both in the X and the Y directions to get the centering.

The advantage here is that you don't have to specify the dimensions for the a element.

.uc-apply-widget1 {
  width: 400px;
  margin: 0 auto;
}
.top {
  background-color: beige;
  height: 10rem;
}
.bottom {
  background-color: lightgray;
  height: 5rem;
  padding: 0 1.6rem 1.6rem 1.6rem;
  position: relative;
}
a {
  display: table;
  width: auto;
  margin: 0 auto;
  padding: 10px;
  border: 1px dotted blue;
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateY(-50%) translateX(-50%);
}
<div class="uc-apply-widget1">
  <div class="top">
  </div>
  <div class="bottom">
    <a>Get Started</a>
  </div>
</div>
相关阅读:
Top