在CSS中使用负边距或填充是不好的做法

时间:2022-12-29 00:02:03

Take for example this image below of a project I am working on... The Blue background is a DIV that is inside of another DIV that wraps all that sidebar contact section together. To get the Blue BG DIV to have the round border and not have a gap because of the parents margin/padding I had to use negative margins
margin: -9px -2px 8px -6px;

以下图中我正在处理的项目为例...蓝色背景是一个DIV,位于另一个DIV中,将所有侧边栏联系部分包装在一起。为了使蓝色BG DIV具有圆形边界而没有间隙,因为父母边距/填充我不得不使用负边距:-9px -2px 8px -6px;

So the question is, is it bad practice to use Negative Margins or Padding?

所以问题是,使用负边距或填充是不好的做法?

在CSS中使用负边距或填充是不好的做法

2 个解决方案

#1


33  

No; it's not bad practice, so long as you're aware of the fact you're using negative margins, and that this necessarily 'pulls'/'moves' elements from their otherwise-'normal' position.

没有;这是不错的做法,只要你知道你使用负边距的事实,并且这必然会“拉动”/“移动”元素从其他“正常”的位置。

Why would you even worry about this?

你为什么要担心这个?

#2


6  

Negative margins are a great way to negate the padding inside of an element for headings etc. I have found no negative results (pardon the pun) of using negative margins. E.g:

负边距是否定标题元素内部填充的好方法。我没有发现使用负边距的负面结果(原谅双关语)。例如:

<div style="padding:10px;border:1px solid blue;">
 <div style="margin:-10px -10px 10px -10px;backgorund-color:yellow;">Full width heading</div>
 The content of the div which is now padded in by ten pixels.
<div>

I was worried about negative margins when I first discovered them but have found them to be very useful is so many layout areas- actually reducing div counts and cleaning up layout code.

当我第一次发现它们时,我担心负边距,但发现它们非常有用的是如此多的布局区域 - 实际上减少了div数并清理了布局代码。

#1


33  

No; it's not bad practice, so long as you're aware of the fact you're using negative margins, and that this necessarily 'pulls'/'moves' elements from their otherwise-'normal' position.

没有;这是不错的做法,只要你知道你使用负边距的事实,并且这必然会“拉动”/“移动”元素从其他“正常”的位置。

Why would you even worry about this?

你为什么要担心这个?

#2


6  

Negative margins are a great way to negate the padding inside of an element for headings etc. I have found no negative results (pardon the pun) of using negative margins. E.g:

负边距是否定标题元素内部填充的好方法。我没有发现使用负边距的负面结果(原谅双关语)。例如:

<div style="padding:10px;border:1px solid blue;">
 <div style="margin:-10px -10px 10px -10px;backgorund-color:yellow;">Full width heading</div>
 The content of the div which is now padded in by ten pixels.
<div>

I was worried about negative margins when I first discovered them but have found them to be very useful is so many layout areas- actually reducing div counts and cleaning up layout code.

当我第一次发现它们时,我担心负边距,但发现它们非常有用的是如此多的布局区域 - 实际上减少了div数并清理了布局代码。