问题
想用vue绑定父文本生成的HTML内容,但是发现CSS样式根本不生效,选择器没起作用
代码:
<div class="announcedetailImg" v-html="detailList.content"></div>
设置样式:
<style lang="less" scoped> .announcedetailImg{ width:100%; } .announcedetailImg img{ width:100% !important; display:block; } .announcedetailImg p{ color:#333; font-size:16px; } </style>
这样之后,发现样式不起作用
解决方案1:
scoped属性导致css仅对当前组件生效(用css3的属性选择器+生成的随机属性实现的),而html绑定渲染出的内容可以理解为是子组件的内容,子组件不会被加上对应的属性,所以不会应用css.
解决的话把scoped属性去掉就行了
解决方案2:
在Vue
组件中,我们可以使用<style scoped>
标签来添加针对该组件的CSS
样式。
<template> <div class="foo"> <div v-html="myHtml"></div> </div> </template> <style scoped> .foo { height: 300px; } </style>
而如果在组件中使用了v-html
,要为myHtml
中的标签添加CSS
样式,我们需要在写样式的时候添加>>>
:
.foo >>> img { max-width: 100%; }
这样,编译时以上CSS
才会被编译为
.foo[data-v-xxxxxxx] img { max-width: 100%; }