Make text not wrap around icon in :before pseudoelement?

早过忘川 提交于 2019-12-10 18:08:01

问题


I have an icon in a :before pseudoelement, and if the textelement becomes to long and goes to the next row, I want it to not wrap around my pseudoelement but keep it's distance.

Here is a link to my example: http://jsbin.com/yosevagaqa/1/edit?html,css,output

If you resize the window so that the text is forces into a new line, you can see the problem.

How can I avoid this?


回答1:


As you can see from the other answers, there are multiple solutions!

If the size of the square in :before is always the same, one other solution would be to add

.link {margin-left:25px; text-indent:-25px;}

to the CSS. This causes the entire block to be shifted to the right, except for the first line, containing the square, which gets "outdented".

http://jsfiddle.net/MrLister/3xbfyqkh/

Or what I would prefer, with sizes in ems, so that the red square depends on the font size.

.link:before {
  /* .. */
  width: 1em; height: 1em;
  margin-right: .5em;
}

.link {margin-left:1.5em; text-indent:-1.5em;}

Making sure, of course, that the indentation is the same as the size + the margin of the square.

http://jsfiddle.net/MrLister/3xbfyqkh/1/

Another approach, since the purpose is to make a custom "bullet", would be to treat the h5 like a list item. Then you won't need the ::before trick. You will need other tricks to make the square the right size though...

.link {
    display:list-item; list-style:square;
    color:red;
    font-size:2em; line-height:.5em;
    margin:.5em 0 .5em 1em}

.link a {
    font-size:.417em; vertical-align:.3em}

http://jsfiddle.net/MrLister/3xbfyqkh/5/




回答2:


You can add following CSS:

.link{
  float: right;
  width: calc(100% - 25px);
}



回答3:


.link{
  position: relative;
  padding-left: 25px;
}
.link:before {
  content: "";
  background: red;
  background-size: contain;
  width: 15px;
  height: 15px;
  display: inline-block;
  vertical-align: middle;
  margin-right: 10px;
  position: absolute; top: 0; left: 0;
}
<h5 class="link"><a href="#">A long link that might wrap and then it gets all weird and stuff</a></h5>


来源:https://stackoverflow.com/questions/30613667/make-text-not-wrap-around-icon-in-before-pseudoelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!