使用 CSS 边距和填充将文本定位在页面右上角

Use CSS margins and padding for positioning text at the top right of a page

我被要求更改我的 CSS,以便在我网站的屏幕右上角添加文本以使用边距和填充,而不是我目前拥有的。 CSS 我目前这样做的是:

<style>
.text-align-top-right{
position: absolute;
top: 10px;
right: 10px;
}
</style>

<div class="text-align-top-right">Some text to align top right</div>

如何使用边距和边距做同样的事情?

提前致谢。

这是一个相当奇怪的请求,当然不是我推荐的定位元素的方式,但是如果这是某种测试,一种方法是使用 css calc公式。

确定屏幕的宽度,然后根据所定位的div的大小调整偏移量。

您需要知道在这种情况下定位的元素的宽度和高度。

.text-align-top-right{
  margin-left:calc(100% - 110px);
  margin-bottom:calc(100% - 110px);
  height:100px;
  width:100px;
  background:#b00;
}
<div class="text-align-top-right">TOP RIGHT</div>

您可以使用下面的 CSS 以非常简单的方式完成它,您可以创建简单的 DIV 并向其中添加 CSS。检查以下代码:

#topRightDisplay{
    position: relative;
}
#topRightDisplay p{
    position: absolute;
    top: 0px;
    right: 0px;
}

<div id="topRightDisplay">
    <p>some text...</p>
</div>

您使用的 <div style="text-align-top-right">Some text to align top right</div> 不正确。您应该替换 class 属性代替 style 属性,然后相应地更改边距和填充以获得所需的结果。

在 HTML

中所做的更改
<div class="text-align-top-right">Some text to align top right</div>

在 CSS 中所做的更改:

.text-align-top-right{
   position: absolute;
   top: 0;
   right: 0;
   margin-top: 30px;
   margin-right: 30px;
}

这是工作 fiddle:https://jsfiddle.net/MasoomS/19Ly9f9t/