将锚标记大小设为div内容?

时间:2016-08-31 11:24:49

标签: html css

下面是一个测试文件test.htm,在Firefox中会生成这个文件:

testhtm

<div>为绿色,边框为黄色,指定尺寸,<a>为红色边框。显然,锚标签的宽度和高度都比它包含的div大。如何使锚标记的大小与div内容相同 - 但是,<div>的大小和位置是否保持不变?基本上,对于此示例和显示的浏览器窗口大小,我想要这个(手动编辑的图片):

testhtm2

test.htm

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <style type="text/css">
body {
  padding:0;
  margin:0;
  width: 100%;
  height: 100%;
  background-color: white;
  color: darkred;
}
div#button {
  margin-top: 2vh;
  padding: 2em;
  width: 20em;
  border-style: solid;
  border-width: 2px;
  border-color: yellow;
  background-color: lightgreen;
  text-align: center;
  font-size: 3vh;
  /* to center div horizontally: */
  margin-left: auto;
  margin-right: auto;
}
a {
  text-decoration: none; /*remove underline of a href link:*/
  display: block;
  width: auto;
  padding: 0;
  margin: 0;
  color: unset;
  border-style: solid;
  border-width: 2px;
  border-color: red;
}
  </style>
</head>

<body>
<br/>
<a href="test.zip" target="_blank"><div id="button">Download this</div></a>
</body>
</html>

2 个答案:

答案 0 :(得分:3)

adisplay: block;更改为display: inline-block; 为了获得完全相同的高度,请删除div的margin-top

为了使其保持居中,请将text-align:center添加到父元素,在您的情况下为body。注意:这样,身体内部的一切都会居中 如果您只想将a - 标记置于中心位置,请在其周围添加包装div并添加text-align:center

Codepen示例:
http://codepen.io/anon/pen/jrNvzx

答案 1 :(得分:1)

试试这个:

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <style type="text/css">
body {
  padding:0;
  margin:0;
  width: 100%;
  height: 100%;
  background-color: white;
  color: darkred;
}
div#button {
  padding: 2em;
  width: 20em;
  border-style: solid;
  border-width: 2px;
  border-color: yellow;
  background-color: lightgreen;
  text-align: center;
  font-size: 3vh;
  /* to center div horizontally: */
  margin-left: auto;
  margin-right: auto;
}
a {
  text-decoration: none; /*remove underline of a href link:*/
  display:inline-block;
  width: auto;
  padding: 0;
  margin: 0;
  color: unset;
  border-style: solid;
  border-width: 2px;
  border-color: red;
}
  </style>
</head>

<body>
<br/>
<a href="test.zip" target="_blank"><div id="button">Download this</div></a>
</body>
</html>